Consul服务注册与发现 Consul配置步骤
consul下载地址
Install | Consul | HashiCorp Developer
启动需要在 下载好的文件夹里 用cmd 运行consul agent -dev启动consul
Consul配置
配置pom
<!--SpringCloud consul config-->
<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>
新增配置bootstrap.yaml
bootstrap.yaml 是系统类配置项 它是最先配置的 优先级最高
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 '-' //Consul k v 键值对命名规则
format: YAML
在主启动类 添加注解
添加@EnableDiscoveryClient //启动服务发现
如果使用RestTemplate作为发起http请求的配置 需要在上面加 @LoadBalanced 启动负载均衡
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate()
{
return new RestTemplate();
}
}
Consul k v 编写规则 config/微服务名称/data
Consul动态刷新
动态刷新 是改了服务配置中心 kv 里面的data后能够实时的获取变化的配置
在主启动类添加@RefreshScope //动态刷新
并在bootstrap.yaml添加
watch:
wait-time: 1
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
watch:
wait-time: 1
ault value is “,”,we update ‘-’
format: YAML
watch:
wait-time: 1