文章目录
7. Consul 服务注册与发现
Consul 官网文档:https://www.consul.io/docs
Consul 下载地址:https://www.consul.io/downloads
7.1 Consul 简介
什么是 Consul?
https://www.consul.io/docs/intro
Consul 是一套开源的分布式服务发现和配置管理系统,由 HashiCorp 公司用 Go 语言开发。
提供了微服务系统中的服务治理、配置中心、控制总线等功能。这些功能中的每一个都可以根据需要单独使用,也可以一起使用以构建全方位的服务网格,总之Consul提供了一种完整的服务网格解决方案。
它具有很多优点。包括:基于 raft 协议,比较简洁;支持健康检查,同时支持 HTTP 和 DNS 协议,支持跨数据中心的 WAN 集群,提供图形界面,跨平台,支持 Linux、Mac、Windows
能干什么?
7.2 安装并运行 Consul
参考:选择自己需要的版本下载安装
https://www.consul.io/downloads
安装使用 Consul
# 更新 yum-utils 工具
yum install -y yum-utils
# 添加 Consul 到仓库
yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
# 下载安装 Consul
yum -y install consul
# 启动 Consul 开发环境
[root@graph2 ~]# consul agent -dev
# 启动 Consul 开发环境,使可以外网访问 Consul UI
[root@graph2 ~]# consul agent -dev -ui -node=consul-dev -client=0.0.0.0
# 后台启动 Consul
[root@graph2 ~]# consul agent -dev -ui -node=consul-dev -client=0.0.0.0 &
# 关闭 Consul
[root@graph2 ~]# consul leave
Graceful leave complete
Consul UI 访问地址
http://47.107.124.79:8500
7.3 服务提供者
在父项目中创建 cloud-provider-consul-payment8006 支付服务module
修改 pom 文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.zzx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-provider-consul-payment8006</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- SpringCloud consul -server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.spring.boot.starter.version}</version>
</dependency>
<dependency>
<groupId>MysqL</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>com.zzx</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
编写 yaml 配置文件
server:
port: 8006
spring:
application:
name: consul-provider-payment
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.MysqL.cj.jdbc.Driver
url: jdbc:MysqL://localhost:3306/springcloud?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8&characterSetResults=UTF-8&autoReconnect=true&allowMultiQueries=true&useSSL=false
username: root
password: 123456
cloud:
# consul 注册中心地址
consul:
host: 47.107.124.79
port: 8500
discovery:
service-name: ${spring.application.name}
# hostname: 47.107.124.79
health-check-url: http://47.107.124.79:8500 # 健康检查地址
heartbeat:
enabled: true # 开启心跳机制
mybatis:
mapper-locations: classpath:mapper/*.xml
config-location: classpath:mybatis-config.xml
编写 springboot 启动类
@SpringBootApplication
@EnablediscoveryClient
public class PaymentConsulMain8006 {
public static void main(String[] args){
SpringApplication.run(PaymentConsulMain8006.class,args);
}
}
编写 mapper、service、controller,参考前面的 payment 模块
7.4 服务消费者
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.zzx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-consumer-consul-order80</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- SpringCloud consul -server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>com.zzx</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
编写 yaml 配置文件
server:
port: 80
spring:
application:
name: cloud-sonsumer-order
cloud:
# consul 注册中心地址
consul:
host: 47.107.124.79
port: 8500
discovery:
service-name: ${spring.application.name}
# hostname: 47.107.124.79
health-check-url: http://47.107.124.79:8500
heartbeat:
enabled: true # 开启心跳机制
编写 springboot 启动类
@SpringBootApplication
@EnablediscoveryClient
public class OrderConsulMain80 {
public static void main(String[] args){
SpringApplication.run(OrderConsulMain80.class,args);
}
}
配置 RestTemplate bean
@Configuration
public class ApplicationContextConfig {
/**
* 注册 RestTemplate
* 并使用 @LoadBalanced 注解开启负载均衡
* @return
*/
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
编写 controller
@RestController
@Slf4j
public class OrderController {
private static final String PAYMENT_URL = "http://consul-provider-payment";
private final RestTemplate restTemplate;
@Autowired
public OrderController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
log.info("payment = {}", JSON.toJSONString(payment));
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
}
启动测试
7.5 三个注册中心的异同点
组件名 | 语言 | CAP | 服务健康检查 | 对外暴露接口 | Spring Cloud 集成 |
---|---|---|---|---|---|
Eureka | Java | AP | 可配支持 | HTTP | 已集成 |
Consul | Go | CP | 支持 | HTTP/DNS | 已集成 |
Zookeeper | Java | CP | 支持 | 客户端 | 已集成 |
CAP原则又称CAP定理,指的是在一个分布式系统中,一致性(Consistency)、可用性(Availability)、分区容错性(Partition tolerance)。CAP 原则指的是,这三个要素最多只能同时实现两点,不可能三者兼顾。
CAP原则的精髓就是要么AP,要么CP,要么AC,但是不存在CAP
- 一致性(C):在分布式系统中的所有数据备份,在同一时刻是否同样的值。(等同于所有节点访问同一份最新的数据副本)
- 可用性(A):保证每个请求不管成功或者失败都有响应。
- 分区容忍性(P):系统中任意信息的丢失或失败不会影响系统的继续运作