Consul微服务的配置中心体验篇

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>

bootstrap.yml

这里要注意是要配置在 bootstrap.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/ 去访问 image

配置config

image

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

总结

  1. 相较于spring cloud config 的配置中心,使用起来较为麻烦,但是对于实时刷新,这块要优于spring cloud config 的,不依赖于中间件的消息通知,也不会出现服务下线的问题。
  2. 这篇文章主要是入门,更高级的使用Consul Config 结合 Git 来做版本控制,请参考我后边的文章
  3. 关于pig:基于Spring Cloud、oAuth2.0开发基于Vue前后分离的开发平台,支持账号、短信、SSO等多种登录,提供配套视频开发教程

猜你喜欢

转载自my.oschina.net/giegie/blog/1634479