温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot应用服务启动与安全终止的示例分析

发布时间:2021-07-08 11:23:19 来源:亿速云 阅读:132 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“SpringBoot应用服务启动与安全终止的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“SpringBoot应用服务启动与安全终止的示例分析”这篇文章吧。

SpringBoot应用服务启动

代码:

package hello;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

  @RequestMapping("/")
  @ResponseBody
  String home() {
    return "Hello World!";
  }

  public static void main(String[] args) throws Exception {
    SpringApplication.run(SampleController.class, args);
  }
}

通过该main()函数作为入口,可以启动SpringBoot服务。虽然这里只有几行代码,当时已经是一个完整的web程序。

有几个注解需要特殊说明一下,我在开发的时候就在这几个注解上吃了不少亏。

@EnableAutoConfiguration:这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。

@ComponentScan:注解搜索beans,并结合@Autowired构造器注入。

@SpringBootApplication:等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan,不过该注解只搜索该包同级的包和下级的包!!!!!!

SpringBoot应用安全终止

由于SpringBoot集成了tomcat,所以当SpringBoot应用启动之后,不能像对普通的tomcat操作一下来操作SpringBoot,不过SpringBoot封装了启动,停止的方法。

SpringBoot,作为Spring框架对“约定优先于配置(Convention Over Configuration)”理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行、产品级别的基于Spring框架的应用,大部分Spring Boot应用只需要非常少的配置就可以快速运行起来,是一个与微服务(MicroServices)相当契合的微框架。

主要有两种方式:通过HTTP发送shutdown信号,或者通过service stop的方式,本文只介绍HTTP方式。

1.在pom.xml中引入actuator依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2.在application.properties文件开启shutdown endpoint,SpringBoot的endpoints.shutdown.enabled默认是关闭的。

#启用shutdown
endpoints.shutdown.enabled=true
#禁用密码验证
endpoints.shutdown.sensitive=false

3.发送停止信号,使用curl向服务器发送post请求:

curl -X POST host:port/shutdown

 将会得到返回消息如下:

{"message":"Shutting down, bye..."}

4.可以看出此方法非常方便,但是也很不安全,正式使用时,必须对该请求进行必要的安全设置,可以借助spring-boot-starter-security进行身份认证:
pom.xml添加security依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
</dependency>

application.properties中变更配置

#开启shutdown的安全验证
endpoints.shutdown.sensitive=true
#验证用户名
security.user.name=admin
#验证密码
security.user.password=secret
#角色
management.security.role=SUPERUSER

 指定路径、IP、端口

#指定shutdown endpoint的路径
endpoints.shutdown.path=/custompath
#也可以统一指定所有endpoints的路径`management.context-path=/manage`
#指定管理端口和IP
management.port=8081
management.address=127.0.0.1

以上是“SpringBoot应用服务启动与安全终止的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI