欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

Spring Cloud - 服务消费者Ribbon

发布时间:2025/7/25 javascript 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Spring Cloud - 服务消费者Ribbon 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

概述

在微服务架构中,业务被拆分为一个个服务,各服务间通过http restful进行通信。Spring Cloud有两种服务调用方式,一种是ribbon + restTemplate,另一种是feign。

创建服务集群

创建两个eureka-hi工程,两者的不同在于启动端口不一样,一个为1002,一个为1003,其余的都一样。

spring.application.name=eureka-hi server.port=1002/1003 eureka.client.service-url.defaultZone=http://localhost:1000/eureka/ 复制代码

创建ribbon

在application类添加@EnableDiscoveryClient注解并注入restTemplate bean

package com.whut.springcloud.eurekaribbon;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate;@SpringBootApplication @EnableDiscoveryClient // 添加@EnableDiscoveryClient,向服务注册中心注册 public class EurekaRibbonApplication {public static void main(String[] args) {SpringApplication.run(EurekaRibbonApplication.class, args);}/***注入restTemplate bean* @LoadBalanced注解:表明restTemplate开启负载均衡功能*/@Bean@LoadBalancedRestTemplate restTemplate(){return new RestTemplate();} }复制代码

编写配置文件

spring.application.name=eureka-ribbon server.port=1004 eureka.client.service-url.defaultZone=http://localhost:1000/eureka/ 复制代码

服务负载均衡测试

  • 编写serveice类
package com.whut.springcloud.eurekaribbon.service;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate;/*** User: Chunguang Li* Date: 2018/3/10* Email: 1192126986@foxmail.com*/@Service public class RibbonService {@Autowiredprivate RestTemplate restTemplate;public String hiService(String name){// 调用EUREKA-HI服务提供的"/hi"方法接口return restTemplate.getForObject("http://EUREKA-HI/hi?name=" + name, String.class);} }复制代码
  • 编写controller类
@RestController public class HiController {@Autowiredprivate RibbonService ribbonService;@GetMapping("/ribbon")public String ribbonController(@RequestParam("name")String name){return ribbonService.hiService(name);} } 复制代码

工作流程

  • 一个服务注册中心 - eureka-server:1000
  • 两个服务提供者 - eureka-hi:1002 eureka-hi:1003,分别向服务注册中心注册
  • 一个负载均衡器 - eureka-ribbon:1004,向服务注册中心注册
  • eureka-ribbon通过restTemplate调用eureka-hi的/hi接口时,因为restTemplate做了负载均衡,所以会轮流调用eureka-hi:1002/1003的/hi接口

总结

以上是生活随笔为你收集整理的Spring Cloud - 服务消费者Ribbon的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。