您的位置:首页 > 编程语言 > Java开发

详解SpringBoot应用服务启动与安全终止

2019-04-29 09:54 453 查看

SpringBoot应用服务启动

参照官方示例工程可以快速搭建简单SpringBoot应用,官方连接如下:http://projects.spring.io/spring-boot/#quick-start
闲话少叙,上代码:

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应用服务启动与安全终止详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SpringBoot 启动 终止