Spring Cloud 与 Consul 服务发现

Consul 服务发现

Consul 是一个开源的服务注册发现工具,采用 Go 语言开发,支持多数据中心分布式高可用的服务发现和配置共享,广泛应用在大规模分布式系统中。

Spring Cloud 原生支持使用 Consul 做服务注册发现,类似 Eureka、ZooKeeper。

下载 Consul 软件,对其运行 consul agent -dev,启动开发模式

在项目中添加依赖

1
compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')

添加 consul 注册中心配置

1
2
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500

打开 http://localhost:8500 查看服务注册情况

服务提供者

service provider 在 5030 端口提供一组管理用户信息的接口:

1
2
3
4
5
6
7
8
9
10
11
@PostMapping("/user")
User addUser(@RequestBody User user);

@GetMapping("/getauser")
User getUser(@RequestParam("id") Integer id);

@GetMapping("/user")
List<User> getAllUser();

@DeleteMapping("/user")
void deleteUser(@RequestParam("id") Integer id);

配置 MySQL 数据库

1
2
3
4
5
spring.datasource.dbcp2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/userdb?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=qqqq
spring.jpa.hibernate.ddl-auto=update

服务消费者

这里使用 feign 调用服务提供者,service consumer 在 5031 端口提供用户信息相关接口

1
2
3
4
5
6
7
8
@PostMapping("/user/add/{name}")
User addUser(@PathVariable("name") String name);

@GetMapping("/user/{id}")
User getUser(@PathVariable("id") Integer id);

@GetMapping("/user")
List<User> getUserList();

执行 post 请求到 http://localhost:5031/user/add/Lerry 向数据库添加一条数据

通过 http://localhost:5031/user 得到用户列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
{
"id": 1,
"name": "Lerry",
"img": "http://up.qqjia.com/z/16/tu17317_45.png",
"sex": "girl",
"age": 20,
"time": 1499761984675
},
{
"id": 4,
"name": "kity",
"img": "http://up.qqjia.com/z/16/tu17317_45.png",
"sex": "girl",
"age": 20,
"time": 1499762171942
}
]

项目源码

https://github.com/yunTerry/spring-cloud-consul