使用Consul代替Spring Cloud Eureka

2018-07-06

随着Eureka 2.0 开源工作宣告停止,其实是可以考虑转战其他方式来实现注册中心了(如:Zookeeper、Redis、Consul等)

本文通过简单的描述,快速将Consul集成到SpringCloud环境中。

Consul环境搭建

官网:https://www.consul.io/

官网提供了(macOS、FreeBSD、Linux、Solaris、Windows)全平台的相关包,下面以Windows为例:

  1. 下载 https://releases.hashicorp.com/consul/1.2.0/consul_1.2.0_windows_amd64.zip
  2. 解压,并创建快速启动脚本:
consul agent -dev
pause

image

  1. 启动,然后浏览器访问:http://localhost:8500, 出现UI界面则搭建成功。

image

将服务注册到Consul

pom.xml

这里列举了集成Consul的核心依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency><!--健康检查相关依赖,后面会用到-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

bootstrap.yml

server:
  port: 8762
spring:
  application:
    name: angercloud-consul
  cloud:
    consul:
      host: localhost
      port: 8500
    discovery:
      client:
        healthCheckInterval: 15s
        instance-id: angercloud-consul
        # 健康检查URI.由spring-boot-starter-actuator提供。
        healthCheckPath: ${management.contextPath}/actuator/health

启动测试

通过注解 @EnableDiscoveryClient 标识该服务为发现客户端,然后根据配置文件注册中Consul

package com.angercloud.registry.consul;

import com.angercloud.support.core.consts.AngerCloudPackages;
import com.angercloud.support.core.web.JSONEntity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wwz
 * @version 1 (2018/7/6)
 * @since Java7
 */
@RestController
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = {
        AngerCloudPackages.SUPPORT_CORE, AngerCloudPackages.REGISTRY_CONSUL
})
public class AngerCloudConsulApplication {

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

    @GetMapping("/sayHello")
    public JSONEntity<?> sayHello() {
        return JSONEntity.ok("Hello, AngerCloudConsulApplication");
    }
}

image

image

image

有关更多细节,后面使用的时候再详细研究(或自己实现redis注册中心)