SpringCloud使用Consul作为注册中心
使用的版本:consul_1.9.5
使用的SpringCloud的版本:Dalston.SR1
作者: 王鹏霄
管理依赖版本文件:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
根据需要引入其对应的项目依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
consul agent -dev启动consul
使用@EnableDiscoveryClient注解使服务具有服务注册的能力,启动应用,注册日志信息
Registering service with consul: NewService{id='consul-client-2001', name='consul-client', tags=[], address='S883FC7EBTTYTNY22', port=2001, enableTagOverride=null, check=Check{script='null', interval=10s, ttl=null, http=http://S883FC7EBTTYTNY22:2001/health, tcp=null, timeout=null, deregisterCriticalServiceAfter=null, tlsSkipVerify=null}, checks=null}
consul报错信息如下:
HTTP GET http://S883FC7EBTTYTNY22:2001/health: 503 Output: {"status":"DOWN"}
解决: 升级SpringCloud版本为H版, Hoxton.SR3
如果有使用到fegin进行服务调用,需要将fegin替换为openfegin
注册信息如下
Registering service with consul: NewService{id='consul-server-2001', name='consul-server', tags=[secure=false], address='S883FC7EBTTYTNY22', meta=null, port=2001, enableTagOverride=null, check=Check{script='null', interval='10s', ttl='null', http='http://S883FC7EBTTYTNY22:2001/actuator/health', method='null', header={}, tcp='null', timeout='null', deregisterCriticalServiceAfter='null', tlsSkipVerify=null, status='null'}, checks=null}
使用Client可以正常调用Server端
在yml文件中添加下面配置指定不同
spring:
application:
name: consul-client
cloud:
consul:
port: 8500
host: localhost
discovery:
heartbeat: true
instance-id: ${spring.application.name}
service-name: name-${spring.application.name}
可以验证其方法调用根据 service-name
新建服务端
指定相同 instance-id: ${spring.application.name}
后者服务会取代前者,无法正常进行服务负载
替换如下配置使instance-id 唯一
instance-id: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}