天天看點

Consul之:服務注冊與發現

一、服務的管理(注冊與發現)有三種方式:

1:通過配置檔案的方式靜态注冊

2:通過HTTP API接口來動态注冊(spring cloud使用方式,spring cloud中使用的是consul api)

3:使用consul client或consul api(程式)實作服務的注冊和發現(Java非spring boot,cloud項目)

1.1、通過配置檔案的方式靜态注冊

1.1.1、建立檔案夾/etc/consul.d,

說明:.d表示一系列配置檔案的存放目錄(directory)

Consul之:服務注冊與發現

1.1.2、建立服務并寫入上述檔案夾中的一個檔案

Consul之:服務注冊與發現

說明:

  • 一個服務我們會配置為json格式:比如上述的單引号之間的形式
  • 一個服務會寫在一個json檔案中

注意:如果上述檔案夾沒有權限進行操作,先改變檔案夾權限,

Consul之:服務注冊與發現

我在window上,示範:

Consul之:服務注冊與發現

1.1.3、先啟動consul程序,帶上config-dir參數

切換螢幕-->

Consul之:服務注冊與發現

window上:D:\soft\worksoft\consul_1.0.6_windows_amd64>consul agent -dev -config-dir etc/consul.d/

Consul之:服務注冊與發現
  • 根據-config-dir指定根據服務注冊的目錄中的檔案來啟動服務。

1.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的值,這點需要注意。

Consul之:服務注冊與發現

結果:

Consul之:服務注冊與發現

1.3:使用Consul client或Consul api實作服務的注冊和發現(Java非spring boot,spring cloud項目)

1.3.1、使用Consul Client

首先加入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之:服務注冊與發現
Consul之:服務注冊與發現

1.3.2、使用Consul API

當然了,還可以使用如下consul api

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

主類:ConsulApiDemo.java

Consul之:服務注冊與發現
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。

二、服務查詢

兩種查詢方式:DNS和HTTP

2.1、DNS:

Consul之:服務注冊與發現

通路的服務名字:

  • tag.servicename.service.consul  tag和servicename都是建立服務的時候配置的
  • DNS通路的端口是8600

2.2、HTTP:

Consul之:服務注冊與發現
  • 通路的路徑:host:port/版本号/catalog/service/服務名
  • Address:用于指定一個特定service的IP位址,預設情況下,使用的是該service使用的agent。

consul client的指令行示範

一、啟動consul server

在安裝好consul的ubuntu虛拟機上啟動consul server,以server方式啟動:

D:\soft\worksoft\consul_1.0.6_windows_amd64>consul agent -ui -server -data-dir=/data -bootstrap-expect 1 -bind 10.200.110.100

Consul之:服務注冊與發現

使用-ui參數啟動server成功後,可以在浏覽器中輸入:http://localhost:8500/ui 看到如下界面

Consul之:服務注冊與發現

二、啟動consul client

在本機上啟動consul client

consul agent -data-dir /data -node=duan -advertise=10.200.110.13 -join=10.200.110.100

加入server節點成功後的截圖如下 

此時在web ui中檢視節點,會發現多了一個節點,但是沒有任何服務 

Consul之:服務注冊與發現

示例:多個服務注冊的情況

4.1、每一個服務注冊到一個檔案

假設現在又建立了一個secondservice服務,我會将該服務寫入secondservice.json檔案中去,如下:

Consul之:服務注冊與發現

使用http去通路:

Consul之:服務注冊與發現

說明:按照服務名去通路。

4.2、多個服務寫在同一個json檔案中

Consul之:服務注冊與發現
  • 放在services中而不是service裡(上邊的單檔案單服務是放在service裡的)
  • 多個服務放在一個數組裡邊
Consul之:服務注冊與發現

注意:在實際開發中,微服務數量衆多,

如果每個檔案都放在一個檔案裡,檔案會非常多,不好!