1. 分布式配置中心
consul不仅可做注册中心,还可做配置中心
applicaiton.yml与bootstrap.yml:
- applicaiton.yml是用户级的资源配置项
- bootstrap.yml是系统级的,优先级更加高
Spring Cloud会创建一个“Bootstrap Context”,作为Spring应用的Application Context
的父上下文。初始化的时候,Bootstrap Context
负责从外部源加载配置属性并解析配置。这两个上下文共享一个从外部获取的Environment
。
2. 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
3. 新增bootstrap.yml
spring:
application:
name: cloud-payment-service
####Spring Cloud Consul for Service Discovery
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
config:
profile-separator: '-' # default value is ",",we update '-'
format: YAML
# config/cloud-payment-service/data
# /cloud-payment-service-dev/data
# /cloud-payment-service-prod/data
修改application.yml
server:
port: 8001
# ==========applicationName + druid-mysql8 driver===================
spring:
# application:
# name: cloud-payment-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2024?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
username: root
password: root
profiles:
active: dev # 多环境配置加载内容dev/prod,不写就是默认default配置
####Spring Cloud Consul for Service Discovery
# cloud:
# consul:
# host: localhost
# port: 8500
# discovery:
# service-name: ${spring.application.name}
# ========================mybatis===================
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.hong.entity
configuration:
map-underscore-to-camel-case: true
4. consul服务器k/v配置填写
配置文件首层目录名必须为config,目录后面带/.官网默认分割方式为**,本文改为-**
最底层文件名必须为data,不带/
5. 测试获取consul中的配置
PayController中添加如下代码
@Value("${server.port}")
private String port;
@GetMapping(value = "/pay/getConfigInfoByConsul")
@Operation(summary = "测试查询consul配置信息",description = "测试查询consul配置信息")
public String getConfigInfoByConsul(@Value("${payment8001.info}") String consulInfo){
return "consulInfo: " + consulInfo +"\t"+ " port: " + port;
}
启动后