Spring Cloud Consul
项目是针对 Consul 的服务治理实现 Consul 是一个分布式高可用的系统, 具有分布式高可用高扩展性
Consul
Consul 是 HashiCorp 公司推出的开源工具, 用于实现分布式系统的服务发现与配置与其他分布式服务注册与发现的方案, Consul 的方案更一站式 , 内置了服务注册与发现框 架具有以下性质:
分布一致性协议实现
健康检查
Key/Value 存储
多数据中心方案
不再需要依赖其他工具 (比如 ZooKeeper 等)
添加依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-consul-all</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-actuator</artifactId>
- </dependency>
consul-all 依赖提供了哪些功能?
- <!-- 消息总线, 提供配置实时刷新, 不再依赖中间件 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-consul-bus</artifactId>
- </dependency>
- <!--consul 的配置中心功能 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-consul-config</artifactId>
- </dependency>
- <!-- 服务注册和发现功能 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-consul-discovery</artifactId>
- </dependency>
- bootstarp.yml
这里要注意是要配置在 bootstarp.yml
- spring:
- application:
- name: pig-consul
- cloud:
- consul:
- host: localhost
- port: 8500
- config:
- enabled: true
- format: KEY_VALUE
- watch:
- enabled: true
- prefix: pig-config
安装 consul
下载: https://www.consul.io/downloads.html
使用:(dev 模式, 生成建议 cluster 模式)
-dev 表示开发模式运行, 使用 - client 参数可指定允许客户端使用什么 ip 去访问, 例如 - client 127.0.0.1 表示可以使用
consul agent -dev -client 127.0.0.1
生产配置参考:
https://www.consul.io/intro/getting-started/join.html
http://127.0.0.1:8500/ui/ 去访问
配置 config
- demo
- @RestController
- public class DemoController {
- @Value("${author}")
- private String author;
- @GetMapping("/demo")
- public String demo() {
- return author;
- }
- }
关于实时刷新配置
- spring:
- cloud:
- consul:
- config:
- watch:
- enabled: true
然后应用要开启定时任务
@EnableScheduling
总结
相较于 spring cloud config 的配置中心, 使用起来较为麻烦, 但是对于实时刷新, 这块要优于 spring cloud config 的, 不依赖于中间件的消息通知, 也不会出现服务下线的问题
这篇文章主要是入门, 更高级的使用 Consul Config 结合 Git 来做版本控制, 请参考我后边的文章
关于 pig: 基于 Spring CloudoAuth2.0 开发基于 vue 前后分离的开发平台, 支持账号短信 SSO 等多种登录, 提供配套视频开发教程
来源: https://juejin.im/post/5aa8af74f265da23826dabf3