Spring Cloud Consul的服务注册与发现

运行Consul

以Windows为例,下载解压后,以开发模式运行:

consul agent --dev

启动成功后,可以访问Consul提供的管理页面,默认端口为8500,页面上显示了已注册服务的列表,包括它们的运行状况等信息。

服务注册

1.添加Spring Cloud Consul依赖:

<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配置:

spring:
 cloud:
 consul:
  host: localhost
  port: 8500

3.运行消费者和提供者服务,Consul管理页面将显示对应的服务信息:

服务发现

使用RestTemplate调用服务

@Autowired
RestTemplate restTemplate;

public String getFirstProduct() {
 return this.restTemplate.getForObject("https://服务名/products/1", String.class);
}

要使用RestTemplate别忘了加配置:

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
	return new RestTemplate();
}

以上就是Spring Cloud Consul的服务注册与发现的详细内容,更多关于Spring Cloud Consul 服务注册与发现的资料请关注呐喊教程其它相关文章!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。