Spring Boot 經常使用註解、Profiles、優雅停服說明

2.1.9 Profiles

在項目的開發中,有些配置文件在不一樣的環境(開發、測試、生成)中配置信息是不一樣的,例如數據庫鏈接信息、Redis配置信息、日誌控制級別等等都是不一樣的,那麼就須要咱們再項目中根據不一樣的環境配置不一樣的配置信息,作到不一樣的環境配置不一樣的配置,作到各個環境配置隔離。java

在 Spring Boot 中多環境配置文件名須要使用 【application-{profile}.properties】或web

【application-{profile}.yml】的格式,這裏 {profile} 對應的是不一樣的環境標識。spring

數據庫

application-test.properties 或 application-test.ymljson

application-prod.properties 或 application-prod.yml安全

需求:markdown

​ 測試環境服務端口:8081,生產環境端口:8082,如何進行實現app

  1. 建立對應環境的配置文件框架

    application-test.yml 和 application-prod.ymlide

    application-test.yml配置文件內容:

    server:
     port: 8081

    application-prod.yml配置文件內容:

    server:
     port: 8082
  2. application.yml激活對應環境配置

    spring:
     profiles:
       active: prod
  3. 測試

    java -jar learn.jar --spring.profiles.active=test

    不一樣的環境啓動腳本中激活不一樣的配置便可。

2.1.10 經常使用註解

註解 說明
@SpringBootApplication 組合註解:等價於@Configuration、@EnableAutoConfiguration、@ComponentScan
@EnableAutoConfiguration 啓用自動配置功能
@ComponentScan 組件掃描,可自動發現和裝配一些Bean
@Import 導入其餘配置類
@Bean 至關於Spring中xml中的bean標籤
@Configuration 標記該類爲配置類,等價於Spring中xml配置文件
@ConditionalOnMissingBean 未在類路徑下中找到對應Bean執行
@ConditionalOnBean 在類路徑下中找到對應Bean執行
@ConditionalOnProperty 在全局配置文件中找到對應屬性執行
@ConditionalOnMissingClass 未在類路徑下中找到對應的Class執行
@ConditionalOnClass 在類路徑下中找到對應的Class執行
@RestController 組合註解,等價於@Controller、@ResponseBody
@Autowired Spring 依賴注入Bean,基於類型byType
@Qualifier 當容器中有多個同類型的Bean,經過該註解來指定,與@Autowired結合使用
@Service 業務類
@Component 組件類
@Repository 數據訪問層

2.1.11 優雅關閉

當線上某個應用須要升級部署時,經常簡單粗暴地使用 kill 命令,這種中止應用的方式會讓應用將全部處理中的請求丟棄,響應失敗。這樣的響應失敗尤爲是在處理重要業務邏輯時須要極力避免的,那麼久須要平滑的關閉。

Spring Boot 框架提供健康監控依賴啓動器,能夠對Spring Boot服務進行監控,優雅停服等功能

2.1.11.1 引入依賴
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
2.1.11.2 添加配置
# 開啓Spring Boot優雅關閉
management.endpoint.shutdown.enabled=true
# 暴露shutdown端點
management.endpoints.web.exposure.include=shutdown
# 自定義管理端點的前綴(保證安全)
management.endpoints.web.base-path=/me-actuator
# 自定義actuator端口
management.server.port=12581
# 不容許遠程管理鏈接(不容許外部調用保證安全)
management.server.address=127.0.0.1
2.1.11.3 測試

執行 kill -9 / 或者 Ctrl+C操做,或者請求接口

http://localhost:12581/me-actuator/shutdown

返回數據

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

說明優雅關閉成功

相關文章
相關標籤/搜索