SpringBoot实战电商项目mall(20k+star)地址:github.com/macrozheng/…html
Spring Cloud Consul 为 SpringBoot 应用提供了 Consul的支持,Consul既能够做为注册中心使用,也能够做为配置中心使用,本文将对其用法进行详细介绍。java
Consul是HashiCorp公司推出的开源软件,提供了微服务系统中的服务治理、配置中心、控制总线等功能。这些功能中的每个均可以根据须要单独使用,也能够一块儿使用以构建全方位的服务网格,总之Consul提供了一种完整的服务网格解决方案。git
Spring Cloud Consul 具备以下特性:github
下载完成后只有一个exe文件,双击运行;spring
在命令行中输入如下命令能够查看版本号:shell
consul --version
复制代码
Consul v1.6.1
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)
复制代码
consul agent -dev
复制代码
咱们经过改造user-service和ribbon-service来演示下服务注册与发现的功能,主要是将应用原来的Eureka注册中心支持改成Consul注册中心支持。bootstrap
建立consul-user-service模块和consul-ribbon-service模块;bash
修改相关依赖,把原来的Eureka注册发现的依赖改成Consul的,并添加SpringBoot Actuator的依赖:app
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
复制代码
server:
port: 8206
spring:
application:
name: consul-user-service
cloud:
consul: #Consul服务注册发现配置
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
复制代码
因为咱们运行了两个consul-user-service,而consul-ribbon-service默认会去调用它的接口,咱们调用consul-ribbon-service的接口来演示下负载均衡功能。负载均衡
屡次调用接口:http://localhost:8308/user/1 ,能够发现两个consul-user-service的控制台交替打印以下信息。
2019-10-20 10:39:32.580 INFO 12428 --- [io-8206-exec-10] c.macro.cloud.controller.UserController : 根据id获取用户信息,用户名称为:macro
复制代码
咱们经过建立consul-config-client模块,并在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>
复制代码
spring:
profiles:
active: dev
复制代码
server:
port: 9101
spring:
application:
name: consul-config-client
cloud:
consul:
host: localhost
port: 8500
discovery:
serviceName: consul-config-client
config:
enabled: true #是否启用配置中心功能
format: yaml #设置配置值的格式
prefix: config #设置配置所在目录
profile-separator: ':' #设置配置的分隔符
data-key: data #配置key的名字,因为Consul是K/V存储,配置存储在对应K的V中
复制代码
/** * Created by macro on 2019/9/11. */
@RestController
@RefreshScope
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/configInfo")
public String getConfigInfo() {
return configInfo;
}
}
复制代码
config/consul-config-client:dev/data
复制代码
config:
info: "config info for dev"
复制代码
config info for dev
复制代码
咱们只要修改下Consul中的配置信息,再次调用查看配置的接口,就会发现配置已经刷新。回想下在使用Spring Cloud Config的时候,咱们须要调用接口,经过Spring Cloud Bus才能刷新配置。Consul使用其自带的Control Bus 实现了一种事件传递机制,从而实现了动态刷新功能。
springcloud-learning
├── consul-config-client -- 用于演示consul做为配置中心的consul客户端
├── consul-user-service -- 注册到consul的提供User对象CRUD接口的服务
└── consul-service -- 注册到consul的ribbon服务调用测试服务
复制代码
mall项目全套学习教程连载中,关注公众号第一时间获取。