运行Consul
以Windows为例,下载解压后,以开发模式运行:
1
|
consul agent --dev
|
启动成功后,可以访问Consul提供的管理页面,默认端口为8500,页面上显示了已注册服务的列表,包括它们的运行状况等信息。
服务注册
1.添加Spring Cloud Consul依赖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
< 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 >
|
2.在服务配置文件中添加Consul配置:
1
2
3
4
5
|
spring:
cloud:
consul:
host: localhost
port: 8500
|
3.运行消费者和提供者服务,Consul管理页面将显示对应的服务信息:
服务发现
使用RestTemplate调用服务
1
2
3
4
5
6
|
@Autowired
RestTemplate restTemplate;
public String getFirstProduct() {
return this .restTemplate.getForObject( "https://服务名/products/1" , String. class );
}
|
要使用RestTemplate别忘了加配置:
1
2
3
4
5
|
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
|
以上就是Spring Cloud Consul的服务注册与发现的详细内容,更多关于Spring Cloud Consul 服务注册与发现的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/seve/p/14001010.html