一、consul简介
Consul是一套开源的分布式服务发现和配置管理系统,是由HashiCorp公司使用Go语言开发的。提供了微服务系统中的服务治理、配置中心、控制总线等功能。这些功能每一个都可以单独使用,也可以构建全方位的服务网格,提供了一套完整的服务器网格解决方案。进入官网
它具有许多优点,包括基于raft协议,比较简洁;支持健康检查,同事支持HTTP和DNS协议,支持跨数据的WAN集群,提供图形界面,跨平台等。
二、安装consul
出于方便的考虑,这里使用的是docker的方式来安装consul
➜ ~ docker pull consul
➜ ~ docker run -d -p 8500:8500 -e CONSUL_BIND_INTERFACE='eth0' --name=dev-consul consul agent -server -bootstrap -ui -client='0.0.0.0'
agent
:启动agent进程-server
:server模式-client
:client模式,以上是绑定客户端接口地址, 0.0.0.0 表示所有地址都可以访问bootstrap
:表示节点是server-leaderui
:启动web ui,默认端口是8500启动容器成功后,访问
http://127.0.0.1:8500
就可以看到consul
的可视化界面了。

三、服务生产者注册
3.1 依赖
<!--consul client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
3.2 改yml
spring:
application:
name: cloud-consul-provide-userinfo-service
cloud:
consul:
host: localhost
port: 8500
discovery:
# 配置服务名称
service-name: ${spring.application.name}
3.3 改启动类
这里和zookeeper一样,都是使用的
@EnableDiscoveryClient
注解
@SpringBootApplication
@EnableDiscoveryClient
public class ConsulProvideApplication8086 {
public static void main(String[] args) {
SpringApplication.run(ConsulProvideApplication8086.class,args);
}
}
启动之后,程序会自动注册到consul
中去,此时访问consul
界面:

四、服务消费者注册
4.1 依赖
<!--consul client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
4.2 改yml
spring:
application:
name: cloud-consule-consume-useradmin
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
4.3 改启动类
@SpringBootApplication
@EnableDiscoveryClient
public class ConsulConsumeApplication8087 {
public static void main(String[] args) {
SpringApplication.run(ConsulConsumeApplication8087.class,args);
}
}
4.4 配置restTemplate
这里要添加
@LoadBalanced
开启了负载均衡才能使用服务名去调用服务
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced // 没有加这个的话没有办法使用服务名来调用接口
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4.5 服务调用
@RestController
@RequestMapping("/user")
public class UserAdminController {
@Resource
RestTemplate restTemplate;
String URL_PREFIX = "http://cloud-consul-provide-userinfo-service";
@GetMapping("/getUser/{userId}")
public BaseResponse getUser(@PathVariable String userId){
ResponseEntity<BaseResponse> forEntity = restTemplate.getForEntity(URL_PREFIX+"/user/getUserById/" + userId, BaseResponse.class);
return forEntity.getBody() ;
}
}
启动之后,程序会自动注册到consul
中去,此时访问consul
界面:

五、Consul其他功能
上面基本是讲的是consul作为注册中心的功能,consul还有许多其他的功能,我们从它的webUI上也可以看到,比如dc1
、 services
、Nodes
、key/value
、ACL
、Intentions
,其中:
- dc1:配置数据中心
- services:服务中心
- nodes:节点中心
- key/value:放置的配置信息
- Acl:访问控制列表
- Intentions:内部控制
更多详情访问 官网文档
网友评论