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 Discoverycloud:consul:host: localhostport: 8500discovery: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-servicedatasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/db2024?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=trueusername: rootpassword: rootprofiles: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/*.xmltype-aliases-package: com.hong.entityconfiguration: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;}
启动后
6. 动态刷新
主启动类上添加@RefreshScope注解
package com.hong;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import tk.mybatis.spring.annotation.MapperScan;/*** @author hong* @date 2020/1/14* @description 支付模块v1启动类*/
@SpringBootApplication
@MapperScan("com.hong.mapper")
@EnableDiscoveryClient
@RefreshScope
public class Main8001 {public static void main(String[] args) {SpringApplication.run(Main8001.class,args);}
}