Spring負(fù)載均衡LoadBalancer使用詳解
LoadBalancer
Spring Cloud LoadBalancer是Spring Cloud官方自己提供的客戶端負(fù)載均衡器, 用來替代Ribbon。
Spring官方提供了兩種客戶端都可以使用loadbalancer:
- RestTemplate:Spring提供的用于訪問Rest服務(wù)的客戶端,RestTemplate提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶端的編寫效率。默認(rèn)情況下,RestTemplate默認(rèn)依賴jdk的HTTP連接工具。
- WebClient:從Spring WebFlux 5.0版本開始提供的一個(gè)非阻塞的基于響應(yīng)式編程的進(jìn)行Http請(qǐng)求的客戶端工具。它的響應(yīng)式編程的基于Reactor的。WebClient中提供了標(biāo)準(zhǔn)Http請(qǐng)求方式對(duì)應(yīng)的get、post、put、delete等方法,可以用來發(fā)起相應(yīng)的請(qǐng)求。
RestTemplate整合LoadBalancer
引入LoadBalancer的依賴
<!-- LoadBalancer --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> <!-- 提供了RestTemplate支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- nacos服務(wù)注冊(cè)與發(fā)現(xiàn) 移除ribbon支持--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <exclusions> <exclusion> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </exclusion> </exclusions> </dependency>
注意:nacos-discovery中引入了ribbon,需要移除ribbon的包,如果不移除,也可以在yml中配置不使用ribbon。
默認(rèn)情況下,如果同時(shí)擁有RibbonLoadBalancerClient和BlockingLoadBalancerClient,為了保持向后兼容性,將使用RibbonLoadBalancerClient。
要覆蓋它,可以設(shè)置spring.cloud.loadbalancer.ribbon.enabled屬性為false。
spring: application: name: user-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848 # 不使用ribbon,使用loadbalancer loadbalancer: ribbon: enabled: false
使用@LoadBalanced注解修飾RestTemplate,開啟客戶端負(fù)載均衡功能
package com.morris.user.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class RestConfig { /** * 默認(rèn)的RestTemplate,不帶負(fù)載均衡 * @return */ @Bean public RestTemplate restTemplate() { return new RestTemplate(); } /** * 有負(fù)責(zé)均衡能力的RestTemplate * @return */ @Bean @LoadBalanced public RestTemplate restTemplate2() { return new RestTemplate(); } }
RestTemplate的使用:
package com.morris.user.controller; import com.morris.user.entity.Order; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("user") public class RestTemplateController { @Resource private RestTemplate restTemplate; @Resource private RestTemplate restTemplate2; @GetMapping("findOrderByUserId") public List<Order> findOrderByUserId(Long userId) { Order[] orders = restTemplate.getForObject("http://127.0.0.1:8020/order/findOrderByUserId?userId=", Order[].class, userId); return Arrays.asList(orders); } @GetMapping("findOrderByUserId2") public List<Order> findOrderByUserId2(Long userId) { Order[] orders = restTemplate2.getForObject("http://order-service/order/findOrderByUserId?userId=", Order[].class, userId); return Arrays.asList(orders); } }
WebClient整合LoadBalancer
引入依賴webflux,WebClient位于webflux內(nèi):
<!-- LoadBalancer --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> <!-- webflux --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <!-- nacos服務(wù)注冊(cè)與發(fā)現(xiàn) --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <exclusions> <exclusion> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </exclusion> </exclusions> </dependency>
同樣需要在配置文件中禁用ribbon:
spring: application: name: user-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848 # 不使用ribbon,使用loadbalancer loadbalancer: ribbon: enabled: false
使用@LoadBalanced注解修飾WebClient.Builder,開啟客戶端負(fù)載均衡功能
package com.morris.user.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class WebClientConfig { @Bean WebClient.Builder webClientBuilder() { return WebClient.builder(); } @Bean @LoadBalanced WebClient.Builder webClientBuilder2() { return WebClient.builder(); } }
WebClient負(fù)載均衡的使用:
package com.morris.user.controller; import com.morris.user.entity.Order; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import javax.annotation.Resource; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("user2") public class WebClientController { @Resource private WebClient.Builder webClientBuilder; @Resource private WebClient.Builder webClientBuilder2; @GetMapping("findOrderByUserId1") public Mono<List<Order>> findOrderByUserId1(Long userId) { return webClientBuilder.build().get().uri("http://127.0.0.1:8020/order/findOrderByUserId?userId=" + userId) .retrieve().bodyToMono(Order[].class).map(t -> Arrays.asList(t)); } @GetMapping("findOrderByUserId2") public Mono<List<Order>> findOrderByUserId2(Long userId) { return webClientBuilder2.build().get().uri("http://order-service/order/findOrderByUserId?userId=" + userId) .retrieve().bodyToMono(Order[].class).map(t -> Arrays.asList(t)); } }
原理:底層會(huì)使用ReactiveLoadBalancer
WebClient設(shè)置Filter實(shí)現(xiàn)負(fù)載均衡
與RestTemplate類似,@LoadBalanced注解的功能是通過SmartInitializingSingleton實(shí)現(xiàn)的。
SmartInitializingSingleton是在所有的bean都實(shí)例化完成之后才會(huì)調(diào)用的,所以在bean的實(shí)例化期間使用@LoadBalanced修飾的WebClient是不具備負(fù)載均衡作用的,比如在項(xiàng)目的啟動(dòng)過程中要使用調(diào)用某個(gè)微服務(wù),此時(shí)WebClient是不具備負(fù)載均衡作用的。
可以通過手動(dòng)為WebClient設(shè)置Filter實(shí)現(xiàn)負(fù)載均衡能力。
@Bean WebClient.Builder webClientBuilder3(ReactorLoadBalancerExchangeFilterFunction lbFunction) { return WebClient.builder().filter(lbFunction); }
到此這篇關(guān)于Spring負(fù)載均衡LoadBalancer使用詳解的文章就介紹到這了,更多相關(guān)Spring負(fù)載均衡LoadBalancer內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Mybatis-plus(MP)中CRUD操作保姆級(jí)筆記
本文主要介紹了Mybatis-plus(MP)中CRUD操作保姆級(jí)筆記,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11如何構(gòu)建可重復(fù)讀取inputStream的request
這篇文章主要介紹了如何構(gòu)建可重復(fù)讀取inputStream的request,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot深入理解之內(nèi)置web容器及配置的總結(jié)
今天小編就為大家分享一篇關(guān)于SpringBoot深入理解之內(nèi)置web容器及配置的總結(jié),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03Java使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)和電話號(hào)碼的方法
今天小編就為大家分享一篇關(guān)于Java使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)和電話號(hào)碼的方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12springboot整合redisson實(shí)現(xiàn)延時(shí)隊(duì)列(附倉庫地址)
延時(shí)隊(duì)列用于管理需要定時(shí)執(zhí)行的任務(wù),對(duì)于大數(shù)據(jù)量和高實(shí)時(shí)性需求,使用延時(shí)隊(duì)列比定時(shí)掃庫更高效,Redisson提供一種高效的延時(shí)隊(duì)列實(shí)現(xiàn)方式,本文就來詳細(xì)的介紹一下,感興趣都可以了解學(xué)習(xí)2024-10-10Nacos?版本不一致報(bào)錯(cuò)Request?nacos?server?failed解決
這篇文章主要為大家介紹了Nacos?版本不一致報(bào)錯(cuò)Request?nacos?server?failed的解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11Java網(wǎng)絡(luò)編程TCP實(shí)現(xiàn)文件上傳功能
這篇文章主要為大家詳細(xì)介紹了Java網(wǎng)絡(luò)編程TCP實(shí)現(xiàn)文件上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07