SpringCloud+Consul 服务注册与服务发现

SpringCloud+Consul 服务注册与服务发现

1. 服务注册:

在Spring.factories有一段:

# Discovery Client Configuration
org.springframework.cloud.client.discovery.EnableDiscoveryClient=
org.springframework.cloud.consul.discovery.ConsulDiscoveryClientConfiguration

这是SpringCloud时Consul实现服务注册的关键。
发现有一个ConsulLifecycle的bean注入:

@Bean
@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
public ConsulLifecycle consulLifecycle(ConsulDiscoveryProperties discoveryProperties,
    HeartbeatProperties heartbeatProperties) {
  ConsulLifecycle lifecycle = new ConsulLifecycle(consulClient, discoveryProperties, heartbeatProperties);
  if (this.ttlScheduler != null) {
    lifecycle.setTtlScheduler(this.ttlScheduler);
  }
  if (this.servletContext != null) {
    lifecycle.setServletContext(this.servletContext);
  }
  if (this.serverProperties != null && this.serverProperties.getPort() != null && this.serverProperties.getPort() > 0) {
    // no need to wait for events for this to start since the user has explicitly set the port.
    lifecycle.setPort(this.serverProperties.getPort());
  }
  return lifecycle;
}

ConsulLifecycle继承自AbstractDiscoveryLifecycle,而AbstractDiscoveryLifecycle实现了ApplicationListener接口,即在容器初始化完成后会调用onApplicationEvent方法。会调用start方法。最终调用register方法注册服务。注意stat()方法的定义:

@Override
@Retryable(interceptor = "consulRetryInterceptor")
public void start() {
  super.start();
}

是支持重新注册的。

//第一个配置
spring:
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        tags: dev
        instance-id: cosulservice
        service-name: app
  application:
    name: cosulservice
server:
  port: 8088
//第二个配置
spring:
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
#        health-check-path: /health
 #       health-check-interval: 15s
        tags: dev
        instance-id: cosulservice2
        service-name: app
  application:
    name: cosulservice
server:
  port: 8088

运行两个应用,注册,查看consul中相关服务:

app
Tags

dev
Nodes
node-client-v-5-1 172.17.0.8 2 passing

    Service 'app' check service:cosulservice2
    passing
    Serf Health Status serfHealth
    passing

node-client-v-5-1 172.17.0.8 2 passing

    Service 'app' check service:cosulservice
    passing
    Serf Health Status serfHealth

注册两个服务。服务均为app。至此已经两个服务已经注册。

2. 服务发现:

@Bean
@ConditionalOnMissingBean
public ConsulDiscoveryClient consulDiscoveryClient(ConsulLifecycle consulLifecycle,
    ConsulDiscoveryProperties discoveryProperties) {
  ConsulDiscoveryClient discoveryClient = new ConsulDiscoveryClient(consulClient,
      consulLifecycle, discoveryProperties);
  discoveryClient.setServerProperties(serverProperties); //null ok
  return discoveryClient;
}
@RequestMapping("/services")
public Object services() {
  return discoveryClient.getInstances("app");
}

简单的单元测试:

@Test
public void testServicess() throws Exception{
  mockMvc.perform(MockMvcRequestBuilders.get("/services").contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(new ResultHandler() {
    @Override
    public void handle(MvcResult result) throws Exception {
      System.out.println(result.getResponse().getContentAsString());
    }
  });
}
[{"serviceId":"app","host":"192.168.1.103","port":8088,"secure":false,"metadata":{"dev":"dev"},"uri":"http://192.168.1.103:8088"},{"serviceId":"app","host":"192.168.1.103","port":8080,"secure":false,"metadata":{"dev":"dev"},"uri":"http://192.168.1.103:8080"}]
原文地址:https://www.cnblogs.com/dragonfei/p/6243297.html