栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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依赖


 org.springframework.boot
 spring-boot-starter-actuator

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依赖


 org.springframework.boot
 spring-boot-starter-security

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号