Consul HTTP API

  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);   
           }
     }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容