2.1.9 Profiles

在项目的开发中,有些配置文件在不同的环境(开发、测试、生成)中配置信息是不同的,例如数据库连接信息、Redis配置信息、日志控制级别等等都是不同的,那么就需要我们再项目中根据不同的环境配置不同的配置信息,做到不同的环境配置不同的配置,做到各个环境配置隔离。

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

【application-{profile}.yml】的格式,这里 {profile} 对应的是不同的环境标识。

application-test.properties 或 application-test.yml

application-prod.properties 或 application-prod.yml

需求:

​ 测试环境服务端口:8081,生产环境端口:8082,如何进行实现

  1. 创建对应环境的配置文件

    application-test.yml 和 application-prod.yml

    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..."}

说明优雅关闭成功