SpringCloud & Consul [Registry]

随着Eureka 2.0 开源工作宣告停止,其实是可以考虑转战其他方式来实现注册中心了(如:Zookeeper、Redis、Consul等)
本文通过简单的描述,快速将Consul集成到SpringCloud环境中。

Consul环境搭建

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

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

1.下载 https://releases.hashicorp.co…

2.解压,并创建快速启动脚本:

consul agent -dev
pause

《SpringCloud & Consul [Registry]》

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

《SpringCloud & Consul [Registry]》

将服务注册到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");
    }
}

《SpringCloud & Consul [Registry]》
《SpringCloud & Consul [Registry]》
《SpringCloud & Consul [Registry]》

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

    原文作者:吴汶泽
    原文地址: https://segmentfault.com/a/1190000015563261
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞