Spring Cloud Consul是针对Consul的服务治理实现,提供服务发现和服务配置。包含了下面几个特性:
- 服务发现
- 健康检查
- Key/Value存储
- 多数据中心
Consul自身提供了服务端,不需要创建服务注册中心,通过命令“$consul agent -dev”启动consul服务端程序的开发模式。 #consul-provider
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
- application.properties
spring.application.name=consul-provider
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8100
- 启动类加注解@EnableDiscoveryClient
consul-consumer
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
- application.properties
spring.application.name=consul-consumer
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8100
- 启动类加注解@EnableDiscoveryClient
- LoadBalancerClient手动调用
@RestController
public class DcController {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
RestTemplate restTemplate;
@GetMapping("/consumer")
public String dc() {
ServiceInstance serviceInstance = loadBalancerClient.choose("consul-provider");
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
return restTemplate.getForObject(url, String.class);
}
}