Spring Cloud整合Consul實現服務註冊和發現

Consul簡介:一款適用於分佈式系統下服務發現和配置的開源工具,支持服務健康檢查、key/value數據存儲、分佈一致性實現、多數據中心方案,並且內置服務註冊和發現框架,支持Spring Cloud集成。

實現準備:

1.Consul獨立下載安裝:https://www.consul.io/downloads.html

2.解壓後只有一個簡單的consul.exe可執行文件,同級目錄下執行consul agent -dev啓動consul服務端即可,在瀏覽器中輸入地址:http://localhost:8500,看到consul界面則表示安裝成功

3.使用版本:springboot使用2.1.5.RELEASE版本、consul依賴使用2.1.1.RELEASE版本

4.新建兩個SpringBoot項目,模擬服務提供者和消費者:consul-provider和consul-consumer

代碼實現

1.在consul-provider中,首先在pom中引入Spring Cloud支持和consul相關依賴:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ccl</groupId>
    <artifactId>consul-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>consul-provider</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- springmvc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 支持健康檢查 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Consul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- spring cloud -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependendies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

然後在application.yml中配置服務端consul:

​
server:
  port: 8019
  servlet:
    context-path: /consulProvider
spring:
  application:
    name: order-service # 應用服務名稱
  cloud:
    consul:
      host: 127.0.0.1 # Consul所在ip
      port: 8500 # Consul監聽端口
      discovery:
        register: true # 配置服務註冊到Consul
        healthCheckPath: ${server.servlet.context-path}/health # 配置Consul實例的服務健康檢查地址,默認爲/health,使用非默認上下文路徑也應修改這裏
        healthCheckInterval: 2s # Consul健康檢查頻率,也叫心跳頻率
        instance-id: ${spring.application.name} # 配置註冊到Consul的服務id
        service-name: ${spring.application.name}
        tags: urlprefis-/${spring.application.name}

​

新建HealthCheckController添加consul需要調用的健康檢查接口。爲了方便把提供服務的方法也寫在這裏。

package com.ccl.consulprovider.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 健康檢查接口
 */
@RestController
public class HealthCheckController {

    // 改路徑需要和配置文件中健康檢查地址保持一致
    @RequestMapping("/health")
    public String healthCheck(){
        return "ok";
    }

    /**
     * 模擬提供服務的方法
     */
    @RequestMapping("/services")
    public Object services(String param1,String param2){
        List<String> pList = new ArrayList<>();
        pList.add(param1);
        pList.add(param2);
        // 模擬業務代碼...
        return pList;
    }
}

同時在開啓類上添加@EnableDiscoveryClient註解,支持向Consul註冊服務:

package com.ccl.consulprovider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient // 自動加載服務註冊、心跳檢測等配置
public class ConsulProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsulProviderApplication.class, args);
    }

}

啓動consul-provider成功後,瀏覽器輸入localhost:8500可以看到order-service,表示服務註冊成功。

2.在consul-consumer中,pom配置和consul-provider一致即可

在application.yml添加客戶端配置:

spring:
  application:
    name: service-client
  cloud:
    consul:
      host: localhost # consul服務端
      port: 8500 # consul服務端監聽端口
      discovery:
        register: false # 不需要註冊到consul上
server:
  port: 8020

注意:實際項目中如果consul-consumer也向其他項目提供服務的話,也需要和consul-provider中有類似配置。這裏spring.cloud.consul.discovery.register置爲false表示不向consul提供服務,所以主類上@EnableDiscoveryClient註解也可省略。

package com.ccl.consulconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient // 已配置spring.cloud.consul.discovery.register=false,客戶端不向consul註冊服務,這個註解也可省略
public class ConsulConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsulConsumerApplication.class, args);
    }

}

新建ApiController訪問consul中服務:

package com.ccl.consulconsumer.controller;

import com.ccl.consulconsumer.domain.OrderEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/getServiceInfo")
    public Object getServiceInfo(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("order-service"); // 服務Id
        System.out.println(serviceInstance);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()
                +"/consulProvider/services?param1={1}&param2={2}";
        return new RestTemplate().getForObject(url, List.class, "hello p1","hello p2");
    }

    /**
     * 從所有服務中選擇一個服務
     */
    @RequestMapping("/discover")
    public Object discover(){
        return loadBalancerClient.choose("order-service").getUri().toString();
    }

    /**
     * 獲取所有服務
     */
    @RequestMapping("/services")
    public Object services(){
        List<ServiceInstance> services = discoveryClient.getInstances("order-service");
        return services;
    }

}

開啓consul-consumer成功後,在瀏覽器中分別輸入:

http://localhost:8020/api/services

http://localhost:8020/api/discover

http://localhost:8020/api/getServiceInfo

界面分別如下:

[{
	"instanceId": "order-service",
	"serviceId": "order-service",
	"host": "DESKTOP-EPG1K4Q",
	"port": 8019,
	"secure": false,
	"metadata": {
		"urlprefis-/order-service": "urlprefis-/order-service",
		"secure": "false",
		"contextPath": "/consulProvider"
	},
	"uri": "http://DESKTOP-EPG1K4Q:8019",
	"scheme": null
}]
http://DESKTOP-EPG1K4Q:8019
["hello p1","hello p2"]

此時就實現了Spring Cloud Consul服務註冊、發現,這裏只描述了單個消費者和單個服務提供者的例子,如果涉及到多服務集羣的需求,參照consul-provider並修改相關host/port以及服務名稱、訪問路徑等配置即可。

更多關於consul的詳細資料,可參看這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章