日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Cloud - 服务消费者Ribbon

發布時間:2025/7/25 javascript 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。