服务注册发现consul之二:在Spring Cloud中使用Consul实现服务的注册和发现
首先安装consul环境,参照之前的文章:《服务注册发现consul之一:consul介绍及安装》中的第一节介绍。
Spring Cloud使用Consul的服务与发现
1、导入依赖pring-cloud-starter-consul-discovery。
2、在其入口文件Application加入注解@EnableDiscoveryClient,开启服务发现(在consul中注册自己)。
3、配置中标明consul信息及自己注册到注册中心的SERVICES和instance-id
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.instance-id=consul-client1
spring.application.name=consul-client1
源码:
spring-cloud-starter-consul-discovery-1.3.3.RELEASE里的pom.xml中引入了spring-cloud-starter-consul,查看spring-cloud-starter-consul-1.3.3.RELEASE.jar中的pom.xml文件中引入了spring-cloud-consul-core和consul-api

再看spring-cloud-consul-core-1.3.3.RELEASE.jar的源代码:
几个配置有:ConsulProperties.java
@ConfigurationProperties("spring.cloud.consul")
@Data
@Validated
public class ConsulProperties {
/** Consul agent hostname. Defaults to 'localhost'. */
@NotNull
private String host = "localhost";
/** Consul agent port. Defaults to '8500'. */
@NotNull
private int port = 8500;
/** Is spring cloud consul enabled */
private boolean enabled = true;
}
RetryProperties.java
@ConfigurationProperties("spring.cloud.consul.retry")
@Data
public class RetryProperties {
/** Initial retry interval in milliseconds. */
private long initialInterval = 1000;
/** Multiplier for next interval. */
private double multiplier = 1.1;
/** Maximum interval for backoff. */
private long maxInterval = 2000;
/** Maximum number of attempts. */
private int maxAttempts = 6;
}
为了演示consul的注册与发现,下面会创建2个服务和1个client端:
一:服务端1:
1、pom.xml
<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> <groupId>com.dxz</groupId>
<artifactId>cloud-server1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>cloud-client</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.RELEASE</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>
server的启动类:ConsulApp.java
package com.dxz.cloud_server; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsulApp { @RequestMapping("/home")
public Object home() {
System.out.println("cloud-server1");
return "cloud-server1";
} public static void main( String[] args ) {
SpringApplication.run(ConsulApp.class, args);
}
}
配置文件application.properties
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.instance-id=consul-server1
spring.application.name=consul-server
server.port=8503
由于我们增加了@EnableDiscoveryClient注解,所以,系统启动的时候,就会向consul注册一个服务,服务的名字为consul-server, ID为consul-server1
启动后,访问:http://localhost:8500/ui/#/dc1/services/consul-server,输出如下页面:

访问consul的HTTP API:http://localhost:8500/v1/catalog/service/consul-server 输出如下:
[
{
"ID": "ae2b2853-18fa-7042-a157-25da30fcc744",
"Node": "DESKTOP-PPSFCNC",
"Address": "127.0.0.1",
"Datacenter": "dc1",
"TaggedAddresses": {
"lan": "127.0.0.1",
"wan": "127.0.0.1"
},
"NodeMeta": {},
"ServiceID": "consul-server1",
"ServiceName": "consul-server",
"ServiceTags": [],
"ServiceAddress": "DESKTOP-PPSFCNC",
"ServicePort": 8503,
"ServiceEnableTagOverride": false,
"CreateIndex": 316,
"ModifyIndex": 719
},
{
"ID": "ae2b2853-18fa-7042-a157-25da30fcc744",
"Node": "DESKTOP-PPSFCNC",
"Address": "127.0.0.1",
"Datacenter": "dc1",
"TaggedAddresses": {
"lan": "127.0.0.1",
"wan": "127.0.0.1"
},
"NodeMeta": {},
"ServiceID": "consul-server2",
"ServiceName": "consul-server",
"ServiceTags": [],
"ServiceAddress": "DESKTOP-PPSFCNC",
"ServicePort": 8504,
"ServiceEnableTagOverride": false,
"CreateIndex": 585,
"ModifyIndex": 721
}
]
二:服务端2
1、pom.xml同上
2、启动类:
package com.dxz.cloud_server; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsulApp { @RequestMapping("/home")
public Object home() {
System.out.println("cloud-server2");
return "cloud-server2";
} public static void main( String[] args ) {
SpringApplication.run(ConsulApp.class, args);
}
}
application.properties 配置内容:(端口、instance-id不同)
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.instance-id=consul-server2
spring.application.name=consul-server
server.port=8504
启动后:

三:客户端
项目依赖,只需要spring-cloud-starter-consul-discovery(我的pom同上)
application.properties 配置内容:
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
spring.cloud.consul.discovery.healthCheckInterval=15s
spring.cloud.consul.discovery.instance-id=consul-client1
spring.application.name=consul-client1
server.port=8501
主类:
package com.dxz.cloud_client; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsulClientApplication { @RequestMapping("/home")
public String home() {
return "hi ,i'm consul client";
} public static void main(String[] args) {
new SpringApplicationBuilder(ConsulClientApplication.class).web(true).run(args);
}
}
主类:ConsulClientApplication.java
package com.dxz.cloud_client; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsulClientApplication { @RequestMapping("/home")
public String home() {
return "hi ,i'm consul client";
} @Autowired
private LoadBalancerClient loadBalancer; @Autowired
private DiscoveryClient discoveryClient; /**
* 从所有服务中选择一个服务(轮询)
*/
@RequestMapping("/discover")
public Object discover() {
return loadBalancer.choose("consul-server").getUri().toString();
} /**
* 获取所有服务
*/
@RequestMapping("/services")
public Object services() {
return discoveryClient.getInstances("consul-server");
} public static void main(String[] args) {
new SpringApplicationBuilder(ConsulClientApplication.class).web(true).run(args);
}
}
启动之后,观看consul如下:

访问http://localhost:8501/services返回如下:
[{"serviceId":"consul-server","host":"DESKTOP-PPSFCNC","port":8503,"secure":false,"metadata":{},"uri":"http://DESKTOP-PPSFCNC:8503"},{"serviceId":"consul-server","host":"DESKTOP-PPSFCNC","port":8504,"secure":false,"metadata":{},"uri":"http://DESKTOP-PPSFCNC:8504"}]
访问:http://localhost:8501/discover
Spring Cloud Consul 配置
核心参数
| 配置项 | 默认值 |
|---|---|
| spring.cloud.consul.enabled | true |
| spring.cloud.consul.host | localhost |
| spring.cloud.consul.port | 8500 |
服务发现参数
| 配置项 | 默认值 |
|---|---|
| spring.cloud.consul.discovery.acl-token | |
| spring.cloud.consul.discovery.catalog-services-watch-delay | 10 |
| spring.cloud.consul.discovery.catalog-services-watch-timeout | 2 |
| spring.cloud.consul.discovery.datacenters | |
| spring.cloud.consul.discovery.default-query-tag | |
| spring.cloud.consul.discovery.default-zone-metadata-name | zone |
| spring.cloud.consul.discovery.deregister | true |
| spring.cloud.consul.discovery.enabled | true |
| spring.cloud.consul.discovery.fail-fast | true |
| spring.cloud.consul.discovery.health-check-critical-timeout | |
| spring.cloud.consul.discovery.health-check-interval | 10s |
| spring.cloud.consul.discovery.health-check-path | /actuator/health |
| spring.cloud.consul.discovery.health-check-timeout | |
| spring.cloud.consul.discovery.health-check-tls-skip-verify | |
| spring.cloud.consul.discovery.health-check-url | |
| spring.cloud.consul.discovery.heartbeat.enabled | false |
| spring.cloud.consul.discovery.heartbeat.interval-ratio | |
| spring.cloud.consul.discovery.heartbeat.ttl-unit | s |
| spring.cloud.consul.discovery.heartbeat.ttl-value | 30 |
| spring.cloud.consul.discovery.hostname | |
| spring.cloud.consul.discovery.instance-group | |
| spring.cloud.consul.discovery.instance-id | 默认为服务名+环境+端口号 |
| spring.cloud.consul.discovery.instance-zone | |
| spring.cloud.consul.discovery.ip-address | |
| spring.cloud.consul.discovery.lifecycle.enabled | true |
| spring.cloud.consul.discovery.management-port | |
| spring.cloud.consul.discovery.management-suffix | management |
| spring.cloud.consul.discovery.management-tags | |
| spring.cloud.consul.discovery.port | |
| spring.cloud.consul.discovery.prefer-agent-address | false |
| spring.cloud.consul.discovery.prefer-ip-address | false |
| spring.cloud.consul.discovery.query-passing | false |
| spring.cloud.consul.discovery.register | true |
| spring.cloud.consul.discovery.register-health-check | true |
| spring.cloud.consul.discovery.scheme | http |
| spring.cloud.consul.discovery.server-list-query-tags | |
| spring.cloud.consul.discovery.service-name | |
| spring.cloud.consul.discovery.tags |
配置服务参数
| 配置项 | 默认值 |
|---|---|
| spring.cloud.consul.config.enabled | true |
| spring.cloud.consul.config.prefix | config |
| spring.cloud.consul.config.default-context | application |
| spring.cloud.consul.config.profile-separator | , |
| spring.cloud.consul.config.data-key | data |
| spring.cloud.consul.config.format | KEY_VALUE, PROPERTIES, YAML, FILES |
| spring.cloud.consul.config.name | ${spring.application.name} |
| spring.cloud.consul.config.acl-token | |
| spring.cloud.consul.config.fail-fast | false |
| spring.cloud.consul.config.watch.enabled | true |
| spring.cloud.consul.config.watch.wait-time | 55 |
| spring.cloud.consul.config.watch.delay | 1000 |
服务注册发现consul之二:在Spring Cloud中使用Consul实现服务的注册和发现的更多相关文章
- spring cloud 专题二(spring cloud 入门搭建 之 微服务搭建和注册)
一.前言 本文为spring cloud 微服务框架专题的第二篇,主要讲解如何快速搭建微服务以及如何注册. 本文理论不多,主要是傻瓜式的环境搭建,适合新手快速入门. 为了更好的懂得原理,大家可以下载& ...
- spring cloud+dotnet core搭建微服务架构:服务发现(二)
前言 上篇文章实际上只讲了服务治理中的服务注册,服务与服务之间如何调用呢?传统的方式,服务A调用服务B,那么服务A访问的是服务B的负载均衡地址,通过负载均衡来指向到服务B的真实地址,上篇文章已经说了这 ...
- spring cloud+.net core搭建微服务架构:服务发现(二)
前言 上篇文章实际上只讲了服务治理中的服务注册,服务与服务之间如何调用呢?传统的方式,服务A调用服务B,那么服务A访问的是服务B的负载均衡地址,通过负载均衡来指向到服务B的真实地址,上篇文章已经说了这 ...
- spring cloud+.net core搭建微服务架构:服务注册(一)
背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...
- 使用Spring Cloud Gateway保护反应式微服务(二)
抽丝剥茧,细说架构那些事——[优锐课] 接着上篇文章:使用Spring Cloud Gateway保护反应式微服务(一) 我们继续~ 将Spring Cloud Gateway与反应式微服务一起使用 ...
- 手把手教你使用spring cloud+dotnet core搭建微服务架构:服务治理(-)
背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...
- spring cloud+dotnet core搭建微服务架构:Api网关(三)
前言 国庆假期,一直没有时间更新. 根据群里面的同学的提问,强烈推荐大家先熟悉下spring cloud.文章下面有纯洁大神的spring cloud系列. 上一章最后说了,因为服务是不对外暴露的,所 ...
- spring cloud+dotnet core搭建微服务架构:配置中心(四)
前言 我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心.一般配置都是存储到配置文件里面,不管多小的配置变动, ...
- spring cloud+dotnet core搭建微服务架构:配置中心续(五)
前言 上一章最后讲了,更新配置以后需要重启客户端才能生效,这在实际的场景中是不可取的.由于目前Steeltoe配置的重载只能由客户端发起,没有实现处理程序侦听服务器更改事件,所以还没办法实现彻底实现这 ...
随机推荐
- Socket远程桌面
自建Socket转发,使用远程桌面(mstsc)连接家中电脑 网络结构图如下: 开题先放图,一切全靠编哈哈. 进入正题! 如图所示,我们需要一个公网服务器,利用公网服务器将内网的数据进行转发,从而 ...
- java-源文件中可以有多个类,但是最多只能有一个public修饰
1.如果源文件中有多个类,那么只能有一个类是public类:如果有一个类是public类,那么源文件的名字必须与这个类的名字完全相同,扩展名是.java. 2.如果源文件中没有public类,那么源文 ...
- rest-framework之响应器(渲染器)
rest-framework之响应器(渲染器) 本文目录 一 作用 二 内置渲染器 三 局部使用 四 全局使用 五 自定义显示模版 回到目录 一 作用 根据 用户请求URL 或 用户可接受的类型,筛选 ...
- Android命令行工具学习总结
15.setting命令 setting命令可以很方便的更改系统设置中的参数(如修改系统默认输入法) 安卓Settings模块浅析:https://www.jianshu.com/p/ed8508fe ...
- Cassandra基础
Apache Cassandra特性 Apache Cassandra由Facebook基于Amazon的Dynamo及其在Google的Bigtable上的数据模型设计开发的面相列的数据库,实现没有 ...
- Architecture options to run a workflow engine
This week a customer called and asked (translated into my own words and shortened): “We do composite ...
- YII2常用知识点总结
YII2常用知识点总结 (一)总结性语句 (1)经常看看yii源码比如vendor\yiisoft\yii2\web这个目录(很重要)下的文件中的方法(这些文件中的公共方法,大致看了下基本上都可以通过 ...
- Unity 3D UI Essentials 学习
Chapter 1: Looking Back,LookingForward Chapter 2: Building Layouts Chapter 3: Control, Control, You ...
- 套接字选项——getsockopt和setsockopt
这两个函数仅用于套接字 #include <sys/socket.h> int getsockopt(int sock, int level, int optname, void *opt ...
- java数据类型取值范围
1个字节:boolean, byte 2个字节:short, char 4个字节:int, float 8个字节:long, double 按照我们初学者的理解1byte=8bit,也就是说1个字节可 ...