Consul HTTP API

2016-07-20  本文已影响754人  torres9gogogo
  1. 服务注册

(1)maven依赖:

    <dependency>
        <groupId>com.orbitz.consul</groupId>
        <artifactId>consul-client</artifactId>
        <version>0.12.4</version>
    </dependency>
</dependencies>
<repositories>
    <repository>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <id>central</id>
        <name>bintray</name>
        <url>http://jcenter.bintray.com</url>
    </repository>
</repositories>```
(2)使用SpringBoot架构
consul的一些配置写在一个配置文件(服务名字、端口):
 public class ConsulConfigProperties {
  /** *服务名字*/
  @Value("${service.name}")
  @NotNull
  private String name;
  /** * 服务对外端口 */
  @Value("${server.port:8080}")
  private int servicePort;
      ...

}```
实现applicationlistener的一个服务注册类:ServiceRegister

public class ServiceRegister implements ApplicationListener<ContextRefreshedEvent> 
{
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event)
        {   
         //获取上面的consul 配置文件 
          ConsulConfigProperties configuration = event.getApplicationContext().getBean(ConsulConfigProperties.class);   
         // 与consul连接 == Consul consul = Consul.builder().build();
          Consul  consul = event.getApplicationContext().getBean(Consul.class); 
        //获取 agent
          AgentClient agent = consul.agentClient();  
        try { 
           // 获取配置中的健康检查URL
           //Consul agent 会来ping这个URL以确定service是否健康     
            URL healthURL  = URI.create(configuration.getHttpUrl()).toURL();     
           //  服务注册 
          //public void register(int port, URL http, long interval, String name, String id, String... tags)  
          //port  注册服务的端口 http 健康检查 interval 健康检查时间间隔  name  服务名字 id 注册ID  tags   注册的tag 比如 Dev  用于consul中取不同的配置。
           agent.register(configuration.getExternalPort(), healthURL, configuration.getHttpInterval(),configuration.getName(), ""+configuration.getExternalPort(), severTag);  
            } 
           catch (MalformedURLException e)
           {      
               throw new RuntimeException(e);   
           }
     }
上一篇 下一篇

猜你喜欢

热点阅读