大佬教程收集整理的这篇文章主要介绍了Consul 入门实战(3)--Spring Cloud Consu 使用,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Cousul 可以作为注册中和配置中心来使用,本来主要介绍 Spring Cloud 整合 Consul 的使用,文中所使用到的软件版本:Java 1.8.0_191、Consul 1.11.1、Spring Boot 2.3.12.RELEASE、Spring Cloud Hoxton.SR12。
<@H_450_10@dependency> <@H_450_10@groupId>org.springframework.boot</@H_450_10@groupId> <@H_450_10@artifactId>spring-boot-starter-actuator</@H_450_10@artifactId> </@H_450_10@dependency> <@H_450_10@dependency> <@H_450_10@groupId>org.springframework.cloud</@H_450_10@groupId> <@H_450_10@artifactId>spring-cloud-starter-consul-discovery</@H_450_10@artifactId> </@H_450_10@dependency>
spring: cloud: consul: host: 10.40.96.20 port: 8500 discovery: register: true prefer-ip-address: true health-check-critical-timeout: 10s #监控检查失败多长时间后,删除注册的服务
如果需要调用的服务在另外一个数据中心,则需要增加 spring.cloud.consul.datacenters 配置;如在本服务在数据中心 dc2,需调用的一个服务(scdemo-server)在另一个数据中心 dc1,则配置如下:
spring: cloud: consul: host: 10.40.96.131 port: 8500 discovery: register: true prefer-ip-address: true datacenters: scdemo-server: dc1 health-check-critical-timeout: 10s #监控检查失败多长时间后,删除注册的服务
注:在使用新版本(SpringBoot 2.4.12/2.4.13/2.5.6/2.5.7/2.5.8、SpringCloud 2020.0.4)时,spring.cloud.consul.datacenters 配置没有效果,还是报找不到服务,应该是新版本还有 bug。
配置完成后,正常启动服务即可。
如果在注册服务是未设置 spring.cloud.consul.discovery.health-check-critical-timeout 参数,可以通过命令行或 API 来删除无效的服务。
命令行:
./consul services deregister -id=scdemo-client-9002
API:
<@H_450_10@dependency> <@H_450_10@groupId>org.springframework.cloud</@H_450_10@groupId> <@H_450_10@artifactId>spring-cloud-starter-consul-config</@H_450_10@artifactId> </@H_450_10@dependency>
spring: cloud: consul: host: 10.40.96.10 port: 8500 config: format: yaml prefix: config #配置所在目录 data-key: data #配置的 key
key 为:config/scdemo-server/data (scdemo-server 为对应的服务名)
value 为:
test:
k1: v1
k2: v22
如下图:
@Autowired private Environment environment; @scheduled(cron = "0/10 * * * * *") public void test() { logger.info("test.k1={}", environment.getProperty("test.k1")); logger.info("test.k2={}", environment.getProperty("test.k2")); }
以上是大佬教程为你收集整理的Consul 入门实战(3)--Spring Cloud Consu 使用全部内容,希望文章能够帮你解决Consul 入门实战(3)--Spring Cloud Consu 使用所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。