溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot應用服務啟動與安全終止的示例分析

發(fā)布時間:2021-07-08 11:23:19 來源:億速云 閱讀:136 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“SpringBoot應用服務啟動與安全終止的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“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()函數(shù)作為入口,可以啟動SpringBoot服務。雖然這里只有幾行代碼,當時已經(jīng)是一個完整的web程序。

有幾個注解需要特殊說明一下,我在開發(fā)的時候就在這幾個注解上吃了不少虧。

@EnableAutoConfiguration:這個注解告訴Spring Boot根據(jù)添加的jar依賴猜測你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration將假定你正在開發(fā)一個web應用并相應地對Spring進行設置。

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

@SpringBootApplication:等價于以默認屬性使用@Configuration,@EnableAutoConfiguration和@ComponentScan,不過該注解只搜索該包同級的包和下級的包?。。。。?!

SpringBoot應用安全終止

由于SpringBoot集成了tomcat,所以當SpringBoot應用啟動之后,不能像對普通的tomcat操作一下來操作SpringBoot,不過SpringBoot封裝了啟動,停止的方法。

SpringBoot,作為Spring框架對“約定優(yōu)先于配置(Convention Over Configuration)”理念的最佳實踐的產(chǎn)物,它能幫助我們很快捷的創(chuàng)建出獨立運行、產(chǎn)品級別的基于Spring框架的應用,大部分Spring Boot應用只需要非常少的配置就可以快速運行起來,是一個與微服務(MicroServices)相當契合的微框架。

主要有兩種方式:通過HTTP發(fā)送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.發(fā)送停止信號,使用curl向服務器發(fā)送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
#也可以統(tǒng)一指定所有endpoints的路徑`management.context-path=/manage`
#指定管理端口和IP
management.port=8081
management.address=127.0.0.1

以上是“SpringBoot應用服務啟動與安全終止的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI