服务注册发现consul之一:spring cloud consul介绍

发布时间:2017-7-1 11:51:22编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"服务注册发现consul之一:spring cloud consul介绍",主要涉及到服务注册发现consul之一:spring cloud consul介绍方面的内容,对于服务注册发现consul之一:spring cloud consul介绍感兴趣的同学可以参考一下。

服务注册发现consul之一:spring cloud consul介绍

一、consul安装

1、到consul的官网下载:https://www.consul.io/downloads.html 

2、解压

3、启动

consul agent -dev

4、验证

用浏览器访问:http://localhost:8500/ui/#/dc1/services

 二、consul介绍

consul 具有以下性质:

  • 服务发现:consul通过http 方式注册服务,并且服务与服务之间相互感应。
  • 服务健康监测
  • key/value 存储
  • 多数据中心

consul可运行在mac windows Linux 等机器上。

三、使用方法

1、导入依赖pring-cloud-starter-consul-discovery。

2、在其入口文件Application加入注解@EnableDiscoveryClient,开启服务发现(在consul中注册自己)。

3、配置中标明consul信息及自己注册到注册中心的SERVICES和instance-id

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.instance-id=consul-client1
spring.application.name=consul-client1

 示例:服务发现consul之二:使用Spring Cloud Consul实现服务的注册和发现

三、服务注册和发现

服务注册 - 服务进程在注册中心注册自己的位置。它通常注册自己的主机和端口号,有时还有身份验证信息,协议,版本号,以及运行环境的详细资料。

服务发现 - 客户端应用进程向注册中心发起查询,来获取服务的位置。服务发现的一个重要作用就是提供一个可用的服务列表。

服务定义的格式类似如下:

{  
  "service":{  
    "id": "jetty",  
    "name": "jetty",  
    "address": "192.168.1.200",  
    "port": 8080,  
    "tags": ["dev"],  
    "checks": [  
        {  
            "http": "http://192.168.1.200:8080/health",  
            "interval": "5s"  
        }  
    ]  
  }  
}  

其中,check是用来做服务的健康检查的,可以有多个,也可以没有,支持多种方式的检查。

check必须是script或者TTL类型的,如果是script类型,则script和interval变量必须被提供,如果是TTL类型,则ttl变量必须被提供

script是consul主动去检查服务的健康状况,ttl是服务主动向consul报告自己的健康状况。

以下是几种配置方式

script check

{  
  "check": {  
    "id": "mem-util",  
    "name": "Memory utilization",  
    "script": "/usr/local/bin/check_mem.py",  
    "interval": "10s",  
    "timeout": "1s"  
  }  
}  

HTTP check:

{  
  "check": {  
    "id": "api",  
    "name": "HTTP API on port 5000",  
    "http": "http://localhost:5000/health",  
    "interval": "10s",  
    "timeout": "1s"  
  }  
}  

TCP check:

{  
  "check": {  
    "id": "ssh",  
    "name": "SSH TCP on port 22",  
    "tcp": "localhost:22",  
    "interval": "10s",  
    "timeout": "1s"  
  }  
}  

TTL check:

{  
  "check": {  
    "id": "web-app",  
    "name": "Web App Status",  
    "notes": "Web app does a curl internally every 10 seconds",  
    "ttl": "30s"  
  }  
}  

注册服务,有三种方式,
1:通过配置文件的方式静态注册
 创建文件夹/etc/consul.d,.d代表有许多配置文件在里面。
vim /etc/consul.d/jetty.json  内容如下:

{  
  "service":{  
    "id": "jetty",  
    "name": "jetty",  
    "address": "192.168.1.200",  
    "port": 8080,  
    "tags": ["dev"],  
    "checks": [  
        {  
            "http": "http://192.168.1.200:8080/health",  
            "interval": "5s"  
        }  
    ]  
  }  
}

重启consul,并将配置文件的路径给consul(指定参数:-config-dir /etc/consul.d)

2:通过HTTP API接口来动态注册
直接调用/v1/agent/service/register接口注册即可,需要注意的是:http method为PUT提交方式

如:

curl -X PUT -d '{"id": "jetty","name": "jetty","address": "192.168.1.200","port": 8080,"tags": ["dev"],"checks": [{"http": "http://192.168.1.104:9020/health","interval": "5s"}]}' http://192.168.1.100:8500/v1/agent/service/register

注意,这种方式,和上面的注册方式有一点不一样,body的参数,是上面service的值,这点需要注意

3:使用程序实现服务的注册和发现(Java非spring boot,cloud项目

首先加入consul client的依赖

<dependency>  
    <groupId>com.orbitz.consul</groupId>  
    <artifactId>consul-client</artifactId>  
    <version>0.15.1</version>  
</dependency>

 主类:ConsulClientDemo.java

package com.dxz.Consul_client;
import java.util.List;

import com.google.common.net.HostAndPort;
import com.orbitz.consul.AgentClient;
import com.orbitz.consul.Consul;
import com.orbitz.consul.HealthClient;
import com.orbitz.consul.model.agent.ImmutableRegCheck;
import com.orbitz.consul.model.agent.ImmutableRegistration;
import com.orbitz.consul.model.health.ServiceHealth;  
  
public class ConsulClientDemo {  
  
    static Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromString("localhost:8500")).withPing(false).build();  
  
    /** 
     * 服务注册 
     */  
    public static void serviceRegister() {  
        AgentClient agent = consul.agentClient();  
          
        //健康检测  
        ImmutableRegCheck check = ImmutableRegCheck.builder().http("http://localhost:9020/health").interval("5s").build();  
          
        ImmutableRegistration.Builder builder = ImmutableRegistration.builder();  
        builder.id("consul-server3").name("consul-server").addTags("v1").address("localhost").port(8080).addChecks(check);  
          
        agent.register(builder.build());  
    }  
      
    /** 
     * 服务获取 
     */  
    public static void serviceGet() {  
        HealthClient client = consul.healthClient();  
        String name = "consul-server";  
        //获取所有服务  
        System.out.println(client.getAllServiceInstances(name).getResponse().size());  
          
        //获取所有正常的服务(健康检测通过的)  
        List<ServiceHealth> responses = client.getHealthyServiceInstances(name).getResponse();
        for(ServiceHealth sh : responses ) {
            System.out.println(sh.getService());
        }
    }  
    
    public static void main(String[] args) {  
        serviceRegister();  
        serviceGet();
        System.exit(0);
    }  
}  

上面的注册后,看consul控制台如下:

当然了,还可以使用如下consul api

        <dependency>
            <groupId>com.ecwid.consul</groupId>
            <artifactId>consul-api</artifactId>
            <version>1.2.2</version>
        </dependency>

主类:ConsulApiDemo.java

package com.dxz.Consul_client;
import java.util.List;
import java.util.Map;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.ConsulRawClient;
import com.ecwid.consul.v1.agent.model.Service;
import com.ecwid.consul.v1.health.model.HealthService;  
  
public class ConsulApiDemo {  
  
  
    public static void serviceApiGet() {
         ConsulRawClient client = new ConsulRawClient("localhost", 8500);  
         ConsulClient consul = new ConsulClient(client);  
         //获取所有服务  
         Map<String, Service> map = consul.getAgentServices().getValue();
         List<HealthService> list = consul.getHealthServices("consul-server", false, null).getValue();
         System.out.println(map.size()+"," +map);
         System.out.println("list" + list);
    }
      
    public static void main(String[] args) {  
        serviceApiGet();  
        System.exit(0);
    }  
}  

结果:

6,map={application=Service{id='application', service='application', tags=[], address='192.168.5.6', port=8080}, consul=Service{id='consul', service='consul', tags=[], address='', port=8300}, consul-client1=Service{id='consul-client1', service='consul-client', tags=[], address='DESKTOP-PPSFCNC', port=8501}, consul-server1=Service{id='consul-server1', service='consul-server', tags=[], address='DESKTOP-PPSFCNC', port=8503}, consul-server2=Service{id='consul-server2', service='consul-server', tags=[], address='DESKTOP-PPSFCNC', port=8504}, consul-server3=Service{id='consul-server3', service='consul-server', tags=[v1], address='localhost', port=8080}}

3,list=[HealthService{node=Node{node='DESKTOP-PPSFCNC', address='127.0.0.1'}, service=Service{id='consul-server1', service='consul-server', tags=[], address='DESKTOP-PPSFCNC', port=8503}, checks=[Node{node='DESKTOP-PPSFCNC', checkId='serfHealth', name='Serf Health Status', status=PASSING, notes='', output='Agent alive and reachable', serviceId='', serviceName=''}, Node{node='DESKTOP-PPSFCNC', checkId='service:consul-server1', name='Service 'consul-server' check', status=CRITICAL, notes='', output='parse http://DESKTOP-PPSFCNC:8503${management.contextPath}/health: invalid character "{" in host name', serviceId='consul-server1', serviceName='consul-server'}]}, HealthService{node=Node{node='DESKTOP-PPSFCNC', address='127.0.0.1'}, service=Service{id='consul-server2', service='consul-server', tags=[], address='DESKTOP-PPSFCNC', port=8504}, checks=[Node{node='DESKTOP-PPSFCNC', checkId='serfHealth', name='Serf Health Status', status=PASSING, notes='', output='Agent alive and reachable', serviceId='', serviceName=''}, Node{node='DESKTOP-PPSFCNC', checkId='service:consul-server2', name='Service 'consul-server' check', status=CRITICAL, notes='', output='parse http://DESKTOP-PPSFCNC:8504${management.contextPath}/health: invalid character "{" in host name', serviceId='consul-server2', serviceName='consul-server'}]}, HealthService{node=Node{node='DESKTOP-PPSFCNC', address='127.0.0.1'}, service=Service{id='consul-server3', service='consul-server', tags=[v1], address='localhost', port=8080}, checks=[Node{node='DESKTOP-PPSFCNC', checkId='serfHealth', name='Serf Health Status', status=PASSING, notes='', output='Agent alive and reachable', serviceId='', serviceName=''}, Node{node='DESKTOP-PPSFCNC', checkId='service:consul-server3', name='Service 'consul-server' check', status=CRITICAL, notes='', output='Get http://localhost:9020/health: dial tcp [::1]:9020: connectex: No connection could be made because the target machine actively refused it.', serviceId='consul-server3', serviceName='consul-server'}]}]

其中,spring cloud 使用的就是第二种consul api


上一篇:删除apache注册表
下一篇:spin_lock & mutex_lock的区别? 【转】 - 张昺华

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款