Consul:强一致性(CP):
1??服务注册相比Eureka会稍慢一些。因为Consul的Raft协议要求必须过半的节点都写入成功才认为注册成功。
2??Leader挂掉后,重新选举期间整个Consul不可用。保证了强一致性,但牺牲了可用性。
Eureka:高可用性和最终一致性(AP):
1??服务注册相对要快,因为不需要等注册信息复制到其他节点,也不保证注册信息是否复制成功。
2??当数据出现不一致的时候,虽然A,B上的注册信息不完全相同,但是每个Eureka节点依然能够正常对外提供服务,这会出现查询服务信息时如果请求A查不到,但请求B就能查到。如果保证了可用性但牺牲了一致性。
Consul不同于Eureka需要单独安装,访问官网可以下载Consul的最新版本,目前使用的是Consul 1.8.4。根据不同的操作系统类型选择不同的安装包,Consul支持所有主流操作系统。
# 从官网下载最新版本的consul服务
wget https://releases.hashicorp.com/consul/1.8.4/consul_1.8.4_linux_amd64.zip
# 使用unzip命令解压
unzip consul_1.8.4_linux_amd64.zip
# 将解压好的consul可执行命令赋值到/usr/local/bin目录下
cp consul /usr/local/bin
# 测试一下
consul
# 以开发者模式快速启动,-client指定客户端可以访问的IP地址
consul agent -dev -client=0.0.0.0
Consul支持健康检查,并提供了HTTP和DNS调用的API接口来完成服务的注册,服务发现以及KV存储这些功能。本人在VMWear中的Linux的IP地址是192.168.32.100。
{
"Datacenter": "dc1",
"Node": "node01",
"Address": "192.168.1.57",
"Service": {
"ID": "mysql-01",
"Service": "mysql",
"tags": [
"master",
"v1"
],
"Address": "192.168.1.57",
"Port": 3306
}
}
含义 | 请求路径 | 请求方式 |
---|---|---|
查看key | v1/kv/:key | GET |
保存或更新 | v1/kv/:key | put |
删除 | /v1/kv/:key | DELETE |
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of department
-- ----------------------------
INSERT INTO `department` VALUES (1, ‘开发部‘);
INSERT INTO `department` VALUES (2, ‘运维部‘);
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES (1, ‘zhangsan‘, ‘男‘);
INSERT INTO `employee` VALUES (2, ‘李四‘, ‘女‘);
-- ----------------------------
-- Table structure for tb_order
-- ----------------------------
DROP TABLE IF EXISTS `tb_order`;
CREATE TABLE `tb_order` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NULL DEFAULT NULL COMMENT ‘用户id‘,
`product_id` int(11) NULL DEFAULT NULL COMMENT ‘商品id‘,
`number` int(11) NULL DEFAULT NULL COMMENT ‘数量‘,
`price` decimal(10, 2) NULL DEFAULT NULL COMMENT ‘单价‘,
`amount` decimal(10, 2) NULL DEFAULT NULL COMMENT ‘总额‘,
`product_name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘商品名‘,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘用户名‘,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for tb_product
-- ----------------------------
DROP TABLE IF EXISTS `tb_product`;
CREATE TABLE `tb_product` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`caption` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`inventory` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`price` decimal(19, 2) NULL DEFAULT NULL,
`product_desc` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`product_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`status` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb_product
-- ----------------------------
INSERT INTO `tb_product` VALUES (1, ‘iPhone‘, ‘1‘, 5000.10, ‘苹果手机就是香‘, ‘苹果哇‘, 50);
-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘用户名‘,
`password` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘密码‘,
`age` int(3) NULL DEFAULT NULL COMMENT ‘年龄‘,
`balance` decimal(10, 2) NULL DEFAULT NULL COMMENT ‘余额‘,
`address` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘地址‘,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
<?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>spring_cloud_demo</artifactId>
<groupId>org.sunxiaping</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product_serivce-consul9003</artifactId>
<dependencies>
<!-- 服务监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
server:
port: 9003 # 微服务的端口号
spring:
application:
name: service-product # 微服务的名称
datasource:
url: jdbc:mysql://192.168.1.57:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
generate-ddl: true
show-sql: true
open-in-view: true
database: mysql
# 微服务info内容详细信息
info:
app.name: xxx
company.name: xxx
build.artifactId: $project.artifactId$
build.version: $project.version$
package com.sunxiaping.product.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "tb_product")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "product_name")
private String productName;
@Column(name = "status")
private Integer status;
@Column(name = "price")
private BigDecimal price;
@Column(name = "product_desc")
private String productDesc;
@Column(name = "caption")
private String caption;
@Column(name = "inventory")
private String inventory;
}
package com.sunxiaping.product.dao;
import com.sunxiaping.product.domain.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
}
package com.sunxiaping.product.service;
import com.sunxiaping.product.domain.Product;
public interface ProductService {
/**
* 根据id查询
*
* @param id
* @return
*/
Product findById(Long id);
/**
* 保存
*
* @param product
*/
void save(Product product);
/**
* 更新
*
* @param product
*/
void update(Product product);
/**
* 删除
*
* @param id
*/
void delete(Long id);
}
package com.sunxiaping.product.service.impl;
import com.sunxiaping.product.dao.ProductRepository;
import com.sunxiaping.product.domain.Product;
import com.sunxiaping.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public Product findById(Long id) {
return productRepository.findById(id).orElse(new Product());
}
@Override
public void save(Product product) {
productRepository.save(product);
}
@Override
public void update(Product product) {
productRepository.save(product);
}
@Override
public void delete(Long id) {
productRepository.deleteById(id);
}
}
package com.sunxiaping.product.controller;
import com.sunxiaping.product.domain.Product;
import com.sunxiaping.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/product")
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping(value = "/save")
public String save(@RequestBody Product product) {
productService.save(product);
return "新增成功";
}
@GetMapping(value = "/findById/{id}")
public Product findById(@PathVariable(value = "id") Long id) {
Product product = productService.findById(id);
return product;
}
}
package com.sunxiaping.product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Product9003Application {
public static void main(String[] args) {
SpringApplication.run(Product9003Application.class, args);
}
}
<?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>spring_cloud_demo</artifactId>
<groupId>org.sunxiaping</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>order-service-consul9004</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
server:
port: 9004 # 微服务的端口号
spring:
application:
name: service-order # 微服务的名称
datasource:
url: jdbc:mysql://192.168.1.57:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
generate-ddl: true
show-sql: true
open-in-view: true
database: mysql
jmx:
unique-names: true
# 微服务info内容详细信息
info:
app.name: xxx
company.name: xxx
build.artifactId: $project.artifactId$
build.version: $project.version$
# 开启日志debug
logging:
level:
root: info
package com.sunxiaping.order.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class SpringConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.sunxiaping.order.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "tb_product")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "product_name")
private String productName;
@Column(name = "status")
private Integer status;
@Column(name = "price")
private BigDecimal price;
@Column(name = "product_desc")
private String productDesc;
@Column(name = "caption")
private String caption;
@Column(name = "inventory")
private String inventory;
}
package com.sunxiaping.order.controller;
import com.sunxiaping.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping(value = "/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping(value = "/buy/{id}")
public Product buy(@PathVariable(value = "id") Long id) {
Product product = restTemplate.getForObject("http://localhost:9003/product/findById/" + id, Product.class);
return product;
}
}
package com.sunxiaping.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Order9004Application {
public static void main(String[] args) {
SpringApplication.run(Order9004Application.class, args);
}
}
<!-- SpringCloud提供的基于Consul的服务发现 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<?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>spring_cloud_demo</artifactId>
<groupId>org.sunxiaping</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product_serivce-consul9003</artifactId>
<dependencies>
<!-- 服务监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- SpringCloud提供的基于Consul的服务发现 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
spring:
# 开始配置Consul的服务注册
cloud:
consul:
# ConsulServer的主机地址
host: 192.168.32.100
# ConsulServer端口
port: 8500
discovery:
# 是否注册
register: true
# 服务实例id 必须填写 也可以写成 {spring.application.name}:${spring.cloud.client.ip-address}
instance-id: ${spring.application.name}-1
# 服务实例名称
service-name: ${spring.application.name}
# 服务实例端口
port: ${server.port}
# 健康检查路径
health-check-path: /actuator/health
# 健康检查时间间隔
health-check-interval: 15s
# 开启IP注册
prefer-ip-address: true
# 实例的请求IP
ip-address: ${spring.cloud.client.ip-address}
server:
port: 9003 # 微服务的端口号
spring:
application:
name: service-product # 微服务的名称
datasource:
url: jdbc:mysql://192.168.1.57:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
generate-ddl: true
show-sql: true
open-in-view: true
database: mysql
# 开始配置Consul的服务注册
cloud:
consul:
# ConsulServer的主机地址
host: 192.168.32.100
# ConsulServer端口
port: 8500
discovery:
# 是否注册
register: true
# 服务实例id 必须填写 也可以写成 {spring.application.name}:${spring.cloud.client.ip-address}
instance-id: ${spring.application.name}-1
# 服务实例名称
service-name: ${spring.application.name}
# 服务实例端口
port: ${server.port}
# 健康检查路径
health-check-path: /actuator/health
# 健康检查时间间隔
health-check-interval: 15s
# 开启IP注册
prefer-ip-address: true
# 实例的请求IP
ip-address: ${spring.cloud.client.ip-address}
# 微服务info内容详细信息
info:
app.name: xxx
company.name: xxx
build.artifactId: $project.artifactId$
build.version: $project.version$
<!-- 服务监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- SpringCloud提供的基于Consul的服务发现 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<?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>spring_cloud_demo</artifactId>
<groupId>org.sunxiaping</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>order-service-consul9004</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 服务监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- SpringCloud提供的基于Consul的服务发现 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
</dependencies>
</project>
spring:
# 开始配置Consul的服务注册
cloud:
consul:
# ConsulServer的主机地址
host: 192.168.32.100
# ConsulServer端口
port: 8500
discovery:
# 是否注册
register: true
# 服务实例id 必须填写 也可以写成 {spring.application.name}:${spring.cloud.client.ip-address}
instance-id: ${spring.application.name}-1
# 服务实例名称
service-name: ${spring.application.name}
# 服务实例端口
port: ${server.port}
# 健康检查路径
health-check-path: /actuator/health
# 健康检查时间间隔
health-check-interval: 15s
# 开启IP注册
prefer-ip-address: true
# 实例的请求IP
ip-address: ${spring.cloud.client.ip-address}
server:
port: 9004 # 微服务的端口号
spring:
application:
name: service-order # 微服务的名称
datasource:
url: jdbc:mysql://192.168.1.57:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
generate-ddl: true
show-sql: true
open-in-view: true
database: mysql
jmx:
unique-names: true
# 开始配置Consul的服务注册
cloud:
consul:
# ConsulServer的主机地址
host: 192.168.32.100
# ConsulServer端口
port: 8500
discovery:
# 是否注册
register: true
# 服务实例id 必须填写 也可以写成 {spring.application.name}:${spring.cloud.client.ip-address}
instance-id: ${spring.application.name}-1
# 服务实例名称
service-name: ${spring.application.name}
# 服务实例端口
port: ${server.port}
# 健康检查路径
health-check-path: /actuator/health
# 健康检查时间间隔
health-check-interval: 15s
# 开启IP注册
prefer-ip-address: true
# 实例的请求IP
ip-address: ${spring.cloud.client.ip-address}
# 微服务info内容详细信息
info:
app.name: xxx
company.name: xxx
build.artifactId: $project.artifactId$
build.version: $project.version$
# 开启日志debug
logging:
level:
root: info
package com.sunxiaping.order.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class SpringConfig {
/**
* SpringCloud对Consul进行了进一步的处理,向其中集成了Ribbon的支持
*
* @return
*/
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.sunxiaping.order.controller;
import com.sunxiaping.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping(value = "/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping(value = "/buy/{id}")
public Product buy(@PathVariable(value = "id") Long id) {
Product product = restTemplate.getForObject("http://service-product/product/findById/" + id, Product.class);
return product;
}
}
- Leader全权负责所有客户端的请求,以及将数据同步到Follower中(同一时刻系统中只存在一个Leader)。
- Follower被动响应请求RPC,从不主动发起RPC。
- Candidate由Follower向Leader转换中间状态。
服务器IP | Consul类型 | Node节点名称 | 序号 |
---|---|---|---|
192.168.237.100 | Server | server-1 | s1 |
192.168.237.101 | Server | server-2 | s2 |
192.168.237.102 | Server | server-3 | s3 |
192.168.237.1 | Client | client-1 | s4 |
简而言之,就是通过VMWear新建3个CentOS7环境,然后每个CentOS7环境中的网络模式都是NAT。
systemctl stop firewalld
systemctl disable firewalld
# 从官网下载最新版本的consul服务
wget https://releases.hashicorp.com/consul/1.8.4/consul_1.8.4_linux_amd64.zip
# 使用unzip命令解压
unzip consul_1.8.4_linux_amd64.zip
# 将解压好的consul可执行命令赋值到/usr/local/bin目录下
cp consul /usr/local/bin
# 测试一下
consul
consul agent -server -bootstrap-expect 3 -data-dir=/etc/consul.d -node=server-1 -bind=192.168.237.100 -ui -client 0.0.0.0 &
consul agent -server -bootstrap-expect 3 -data-dir=/etc/consul.d -node=server-2 -bind=192.168.237.101 -ui -client 0.0.0.0 &
consul agent -server -bootstrap-expect 3 -data-dir=/etc/consul.d -node=server-3 -bind=192.168.237.102 -ui -client 0.0.0.0 &
-server:以server身份启动
-bootstrap-expect:集群要求的最少Server数量,当低于这个数量,集群将失效
-data-dir:data存放的目录。
-node:节点id,在同一集群中不能重复。
-bind:监听的IP地址。
-client:客户端的IP地址(0.0.0.0)表示不限制。
&:在后台运行,Linux脚本语法
consul agent -data-dir /etc/consul.d -node=client-1 -bind=192.168.237.1 -client=0.0.0.0
## 加入到consul集群
consul join 192.168.237.100
# 查看consul集群节点信息
consul members
server:
port: 9003 # 微服务的端口号
spring:
application:
name: service-product # 微服务的名称
datasource:
url: jdbc:mysql://192.168.237.100:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
generate-ddl: true
show-sql: true
open-in-view: true
database: mysql
# 开始配置Consul的服务注册
cloud:
consul:
# Consul Client的地址 修改的地方
host: 192.168.237.1
# ConsulServer端口
port: 8500
discovery:
# 是否注册
register: true
# 服务实例id 必须填写 也可以写成 {spring.application.name}:${spring.cloud.client.ip-address}
instance-id: ${spring.application.name}-1
# 服务实例名称
service-name: ${spring.application.name}
# 服务实例端口
port: ${server.port}
# 健康检查路径
health-check-path: /actuator/health
# 健康检查时间间隔
health-check-interval: 15s
# 开启IP注册
prefer-ip-address: true
# 实例的请求IP
ip-address: ${spring.cloud.client.ip-address}
# 微服务info内容详细信息
info:
app.name: xxx
company.name: xxx
build.artifactId: $project.artifactId$
build.version: $project.version$
server:
port: 9004 # 微服务的端口号
spring:
application:
name: service-order # 微服务的名称
datasource:
url: jdbc:mysql://192.168.237.100:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
jpa:
generate-ddl: true
show-sql: true
open-in-view: true
database: mysql
jmx:
unique-names: true
# 开始配置Consul的服务注册
cloud:
consul:
# Consul Client的地址 修改的地方
host: 192.168.237.1
# ConsulServer端口
port: 8500
discovery:
# 是否注册
register: true
# 服务实例id 必须填写 也可以写成 {spring.application.name}:${spring.cloud.client.ip-address}
instance-id: ${spring.application.name}-1
# 服务实例名称
service-name: ${spring.application.name}
# 服务实例端口
port: ${server.port}
# 健康检查路径
health-check-path: /actuator/health
# 健康检查时间间隔
health-check-interval: 15s
# 开启IP注册
prefer-ip-address: true
# 实例的请求IP
ip-address: ${spring.cloud.client.ip-address}
# 微服务info内容详细信息
info:
app.name: xxx
company.name: xxx
build.artifactId: $project.artifactId$
build.version: $project.version$
# 开启日志debug
logging:
level:
root: info
# PUT请求
http://192.168.32.100:8500/v1/catalog/deregister
# PUT请求
http://192.168.32.100:8500/v1/agent/service/deregister/[service-id]
consul leave
命令,或者在其他节点使用consul force-level 节点id
。原文:https://www.cnblogs.com/xuweiweiwoaini/p/13736652.html