Spring Boot 2.X中Consul如何利用RestTemplate进行服务间调用?

2026-06-09 08:182阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1395个文字,预计阅读时间需要6分钟。

Spring Boot 2.X中Consul如何利用RestTemplate进行服务间调用?

这篇文章简要介绍了如何使用Spring Boot 2.X和Consul通过RestTemplate实现服务调用。以下是一个示例代码,展示了如何使用RestTemplate进行服务调用,内容简洁,适合快速学习和参考。

java@RestControllerpublic class ServiceController {

@Autowired private RestTemplate restTemplate;

@Autowired private ConsulDiscoveryClient consulDiscoveryClient;

@GetMapping(/service) public String callService() { String serviceName=target-service; String serviceUrl=consulDiscoveryClient.getService(serviceName).getHealthyInstance().getUri().toString(); String result=restTemplate.getForObject(serviceUrl, String.class); return result; }}

这段代码首先通过ConsulDiscoveryClient获取目标服务的URL,然后使用RestTemplate进行服务调用,并返回结果。对于需要了解Spring Boot 2.X和Consul的详细学习资料,建议参考以下资源:

1. Spring Boot官方文档:https://docs.spring.io/spring-boot/docs/current/reference/single/

2.Consul官方文档:https://www.consul.io/docs/

3.Spring Cloud官方文档:https://spring.io/projects/spring-cloud

这些资源可以帮助您深入了解Spring Boot、Consul和Spring Cloud的相关知识,提高学习和工作效率。

这篇文章主要介绍了spring boot2X Consul如何通过RestTemplate实现服务调用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Consul可以用于实现分布式系统的服务发现与配置

服务调用有两种方式:

A.使用RestTemplate 进行服务调用

负载均衡——通过Ribbon注解RestTemplate

B.使用Feign 进行声明式服务调用

负载均衡——默认使用Ribbon实现

先使用RestTemplate来实现

1.服务注册发现中心

启动Consul

consul agent -dev

2.服务端

在spring boot2X整合Consul 的基础上

添加服务provider,provider1

provider测试方法

package com.xyz.provider.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class demoController { @RequestMapping("/hello") public String Hello(){ return "hello,provider"; } }

provider1测试方法

package com.xyz.provider1.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class demoController { @RequestMapping("/hello") public String Hello(){ return "hello,another provider"; } }

启动provider和provider1

浏览器访问localhost:8500

有两个服务提供者节点实例

3.客户端

(1)添加依赖

<properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR4</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>

(2)添加配置

server.port=8015 spring.application.name=xyz-comsumer spring.cloud.consul.host=localhost spring.cloud.consul.port=8500 spring.cloud.consul.discovery.register=false spring.cloud.consul.discovery.health-check-url=/actuator/health spring.cloud.consul.discovery.heartbeat.enabled=true management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always

(3)测试方法

获取所有注册的服务,从注册的服务中选取一个,服务调用

package com.xyz.comsumer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class HelloController { @Autowired private LoadBalancerClient loadBalancer; @Autowired private DiscoveryClient discoveryClient; private String serviceName = "service-provider"; @RequestMapping("/services") public Object services() { return discoveryClient.getInstances(serviceName); } @RequestMapping("/discover") public Object discover() { return loadBalancer.choose(serviceName).getUri().toString(); } @RequestMapping("/hello") public String hello() { ServiceInstance serviceInstance = loadBalancer.choose(serviceName); String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class); return callServiceResult; } }

注:

客户端调用的服务名,是在服务端指定的,在服务端配置里使用 spring.cloud.consul.discovery.service-name指注册到 Consul 的服务名称

测试

启动Consul

启动provider和provider1

启动comsumer

测试地址 localhost:8015/services

返回结果

Spring Boot 2.X中Consul如何利用RestTemplate进行服务间调用?

[ { "instanceId": "provider-8010", "serviceId": "service-provider", "host": "hkgi-PC", "port": 8010, "secure": false, "metadata": { "secure": "false" }, "uri": "hkgi-PC:8010", "scheme": null }, { "instanceId": "provider-8011", "serviceId": "service-provider", "host": "hkgi-PC", "port": 8011, "secure": false, "metadata": { "secure": "false" }, "uri": "hkgi-PC:8011", "scheme": null } ]

测试地址 localhost:8015/discover

返回结果

  •   hkgi-PC:8011 或 hkgi-PC:8011
  •   测试地址 localhost:8015/hello
  •   返回结果
  •   hello,provider 或 hello,another provider

注:

结果交替出现的,这是因为负载均衡器是采用的是轮询的方式

说明:

调用的过程:

A.通过LoadBalancerClient查询服务

B.通过RestTemplate调用远程服务

Ribbon负载均衡策略

  •   BestAvailableRule
  •   AvailabilityFilteringRule
  •   WeightedResponseTimeRule
  •   RetryRule
  •   RoundRobinRule
  •   RandomRule
  •   ZoneAvoidanceRule

自定义Ribbon负载均衡——使用随机访问策略

修改启动类

package com.xyz.comsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class ComsumerApplication { public static void main(String[] args) { SpringApplication.run(ComsumerApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }

服务调用

package com.xyz.comsumer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class RibbonHelloController { @Autowired private RestTemplate restTemplate; private String serviceName = "service-provider"; @RequestMapping("/ribbon/hello") public String hello() { String callServiceResult = restTemplate.getForObject(""+serviceName+"/hello", String.class); return callServiceResult; } }

配置添加

service-provider.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

重新启动 comsumer

测试地址 localhost:8015/ribbon/hello

输出的结果不再是交替出现,改为随机的了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计1395个文字,预计阅读时间需要6分钟。

Spring Boot 2.X中Consul如何利用RestTemplate进行服务间调用?

这篇文章简要介绍了如何使用Spring Boot 2.X和Consul通过RestTemplate实现服务调用。以下是一个示例代码,展示了如何使用RestTemplate进行服务调用,内容简洁,适合快速学习和参考。

java@RestControllerpublic class ServiceController {

@Autowired private RestTemplate restTemplate;

@Autowired private ConsulDiscoveryClient consulDiscoveryClient;

@GetMapping(/service) public String callService() { String serviceName=target-service; String serviceUrl=consulDiscoveryClient.getService(serviceName).getHealthyInstance().getUri().toString(); String result=restTemplate.getForObject(serviceUrl, String.class); return result; }}

这段代码首先通过ConsulDiscoveryClient获取目标服务的URL,然后使用RestTemplate进行服务调用,并返回结果。对于需要了解Spring Boot 2.X和Consul的详细学习资料,建议参考以下资源:

1. Spring Boot官方文档:https://docs.spring.io/spring-boot/docs/current/reference/single/

2.Consul官方文档:https://www.consul.io/docs/

3.Spring Cloud官方文档:https://spring.io/projects/spring-cloud

这些资源可以帮助您深入了解Spring Boot、Consul和Spring Cloud的相关知识,提高学习和工作效率。

这篇文章主要介绍了spring boot2X Consul如何通过RestTemplate实现服务调用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Consul可以用于实现分布式系统的服务发现与配置

服务调用有两种方式:

A.使用RestTemplate 进行服务调用

负载均衡——通过Ribbon注解RestTemplate

B.使用Feign 进行声明式服务调用

负载均衡——默认使用Ribbon实现

先使用RestTemplate来实现

1.服务注册发现中心

启动Consul

consul agent -dev

2.服务端

在spring boot2X整合Consul 的基础上

添加服务provider,provider1

provider测试方法

package com.xyz.provider.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class demoController { @RequestMapping("/hello") public String Hello(){ return "hello,provider"; } }

provider1测试方法

package com.xyz.provider1.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class demoController { @RequestMapping("/hello") public String Hello(){ return "hello,another provider"; } }

启动provider和provider1

浏览器访问localhost:8500

有两个服务提供者节点实例

3.客户端

(1)添加依赖

<properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR4</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>

(2)添加配置

server.port=8015 spring.application.name=xyz-comsumer spring.cloud.consul.host=localhost spring.cloud.consul.port=8500 spring.cloud.consul.discovery.register=false spring.cloud.consul.discovery.health-check-url=/actuator/health spring.cloud.consul.discovery.heartbeat.enabled=true management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always

(3)测试方法

获取所有注册的服务,从注册的服务中选取一个,服务调用

package com.xyz.comsumer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class HelloController { @Autowired private LoadBalancerClient loadBalancer; @Autowired private DiscoveryClient discoveryClient; private String serviceName = "service-provider"; @RequestMapping("/services") public Object services() { return discoveryClient.getInstances(serviceName); } @RequestMapping("/discover") public Object discover() { return loadBalancer.choose(serviceName).getUri().toString(); } @RequestMapping("/hello") public String hello() { ServiceInstance serviceInstance = loadBalancer.choose(serviceName); String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class); return callServiceResult; } }

注:

客户端调用的服务名,是在服务端指定的,在服务端配置里使用 spring.cloud.consul.discovery.service-name指注册到 Consul 的服务名称

测试

启动Consul

启动provider和provider1

启动comsumer

测试地址 localhost:8015/services

返回结果

Spring Boot 2.X中Consul如何利用RestTemplate进行服务间调用?

[ { "instanceId": "provider-8010", "serviceId": "service-provider", "host": "hkgi-PC", "port": 8010, "secure": false, "metadata": { "secure": "false" }, "uri": "hkgi-PC:8010", "scheme": null }, { "instanceId": "provider-8011", "serviceId": "service-provider", "host": "hkgi-PC", "port": 8011, "secure": false, "metadata": { "secure": "false" }, "uri": "hkgi-PC:8011", "scheme": null } ]

测试地址 localhost:8015/discover

返回结果

  •   hkgi-PC:8011 或 hkgi-PC:8011
  •   测试地址 localhost:8015/hello
  •   返回结果
  •   hello,provider 或 hello,another provider

注:

结果交替出现的,这是因为负载均衡器是采用的是轮询的方式

说明:

调用的过程:

A.通过LoadBalancerClient查询服务

B.通过RestTemplate调用远程服务

Ribbon负载均衡策略

  •   BestAvailableRule
  •   AvailabilityFilteringRule
  •   WeightedResponseTimeRule
  •   RetryRule
  •   RoundRobinRule
  •   RandomRule
  •   ZoneAvoidanceRule

自定义Ribbon负载均衡——使用随机访问策略

修改启动类

package com.xyz.comsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class ComsumerApplication { public static void main(String[] args) { SpringApplication.run(ComsumerApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }

服务调用

package com.xyz.comsumer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class RibbonHelloController { @Autowired private RestTemplate restTemplate; private String serviceName = "service-provider"; @RequestMapping("/ribbon/hello") public String hello() { String callServiceResult = restTemplate.getForObject(""+serviceName+"/hello", String.class); return callServiceResult; } }

配置添加

service-provider.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

重新启动 comsumer

测试地址 localhost:8015/ribbon/hello

输出的结果不再是交替出现,改为随机的了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。