Spring負(fù)載均衡LoadBalancer使用詳解
LoadBalancer
Spring Cloud LoadBalancer是Spring Cloud官方自己提供的客戶端負(fù)載均衡器, 用來(lái)替代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等方法,可以用來(lái)發(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)文章
SpringBoot?@Scheduled?Cron表達(dá)式使用方式
這篇文章主要介紹了SpringBoot?@Scheduled?Cron表達(dá)式使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03
Java創(chuàng)建圖形用戶界面(GUI)入門詳細(xì)指南(Swing庫(kù)JFrame類)
這篇文章主要介紹了使用Java?Swing庫(kù)的JFrame類創(chuàng)建基本的圖形用戶界面,包括窗口的創(chuàng)建、組件的添加和事件處理,通過代碼講解了如何設(shè)置窗口大小、添加按鈕及處理按鈕點(diǎn)擊事件,適合初學(xué)者學(xué)習(xí)和開發(fā)GUI應(yīng)用程序,需要的朋友可以參考下2024-11-11
springBoot+webMagic實(shí)現(xiàn)網(wǎng)站爬蟲的實(shí)例代碼
這篇文章主要介紹了springBoot+webMagic實(shí)現(xiàn)網(wǎng)站爬蟲的實(shí)例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
SpringBoot多環(huán)境開發(fā)該如何配置
這篇文章主要介紹了 SpringBoot多環(huán)境的開發(fā)配置詳情,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-09-09
org.slf4j.Logger中info()方法的使用詳解
這篇文章主要介紹了org.slf4j.Logger中info()方法的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
IDEA連接mysql報(bào)錯(cuò)的問題及解決方法
這篇文章主要介紹了IDEA連接mysql報(bào)錯(cuò)的問題及解決方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
java通過Callable和Future來(lái)接收線程池的執(zhí)行結(jié)果
這篇文章主要介紹了java通過Callable和Future來(lái)接收線程池的執(zhí)行結(jié)果,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

