02 Spring Cloud Consul

Wu Jun 2019-01-05 17:03:30
10 微服务 > 0 服务注册与发现

Spring Cloud Consul是针对Consul的服务治理实现,提供服务发现和服务配置。包含了下面几个特性:

Consul自身提供了服务端,不需要创建服务注册中心,通过命令“$consul agent -dev”启动consul服务端程序的开发模式。 #consul-provider

  1. pom
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
  1. application.properties
spring.application.name=consul-provider

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8100
  1. 启动类加注解@EnableDiscoveryClient

consul-consumer

  1. pom
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
  1. application.properties
spring.application.name=consul-consumer

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8100
  1. 启动类加注解@EnableDiscoveryClient
  2. 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);
    }

}