当前位置: 移动技术网 > IT编程>开发语言>Java > 详解SpringBoot应用服务启动与安全终止

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

2019年07月19日  | 移动技术网IT编程  | 我要评论
springboot应用服务启动 参照官方示例工程可以快速搭建简单springboot应用,官方连接如下: 闲话少叙,上代码: package hello;

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应用服务启动与安全终止详解整合,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网