sentinel整合ribbon與fallback流程分步講解
前期準(zhǔn)備:
啟動(dòng)nacos和sentinel
提供者9003/9004(以9003為樣本)
新建cloudalibaba-provider-payment9003/9004
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mscloud03</artifactId>
<groupId>com.atguigu.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-provider-payment9003</artifactId>
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><!-- 引入自己定義的api通用包,可以使用Payment支付Entity -->
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!-- SpringBoot整合Web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>yml文件
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
配置9004的時(shí)候記得修改端口
主啟動(dòng)類(lèi)
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003
{
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class, args);
}
}業(yè)務(wù)類(lèi)
@RestController
public class PaymentController
{
@Value("${server.port}")
private String serverPort;
public static HashMap<Long,Payment> hashMap = new HashMap<>();
static
{
hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
}
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
{
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort: "+serverPort,payment);
return result;
}
}測(cè)試1
啟動(dòng)9003訪問(wèn)localhost:9003/paymentSQL/1

消費(fèi)者84
新建cloudalibaba-consumer-nacos-order84
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mscloud03</artifactId>
<groupId>com.atguigu.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-consumer-nacos-order84</artifactId>
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--SpringCloud ailibaba sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 引入自己定義的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!-- SpringBoot整合Web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>yml文件
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默認(rèn)8719端口,假如被占用會(huì)自動(dòng)從8719開(kāi)始依次+1掃描,直至找到未被占用的端口
port: 8719
#消費(fèi)者將要去訪問(wèn)的微服務(wù)名稱(chēng)(注冊(cè)成功進(jìn)nacos的微服務(wù)提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
主啟動(dòng)
@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain84
{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}配置類(lèi)
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}業(yè)務(wù)類(lèi)1
@RestController
@Slf4j
public class CircleBreakerController
{
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback")
public CommonResult<Payment> fallback(@PathVariable Long id)
{
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法參數(shù)異常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,該ID沒(méi)有對(duì)應(yīng)記錄,空指針異常");
}
return result;
}
}測(cè)試2
啟動(dòng)9003 9004 84
訪問(wèn)http://localhost:84/consumer/fallback/1

再訪問(wèn)http://localhost:84/consumer/fallback/1

可以發(fā)現(xiàn)第一次是9004端口,第二次是9003端口,這里面的話,就可以就知道意見(jiàn)實(shí)現(xiàn)了ribbon中的輪訓(xùn)
測(cè)試3
訪問(wèn)http://localhost:84/consumer/fallback/4

http://localhost:84/consumer/fallback/4
給客戶error頁(yè)面,不友好
修改業(yè)務(wù)類(lèi)(只配置fallback)
@RestController
@Slf4j
public class CircleBreakerController
{
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback負(fù)責(zé)業(yè)務(wù)異常
public CommonResult<Payment> fallback(@PathVariable Long id)
{
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法參數(shù)異常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,該ID沒(méi)有對(duì)應(yīng)記錄,空指針異常");
}
return result;
}
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"兜底異常handlerFallback,exception內(nèi)容 "+e.getMessage(),payment);
}
}
本例sentinel無(wú)配置
測(cè)試4
訪問(wèn)http://localhost:84/consumer/fallback/4

這里可以發(fā)現(xiàn)沒(méi)有出現(xiàn)error界面,而是我們自己配置的兜底的處理方案
修改業(yè)務(wù)類(lèi)(只配置blockHandler )
@RestController
@Slf4j
public class CircleBreakerController
{
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler負(fù)責(zé)在sentinel里面配置的降級(jí)限流
public CommonResult<Payment> fallback(@PathVariable Long id)
{
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("非法參數(shù)異常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,該ID沒(méi)有對(duì)應(yīng)記錄");
}
return result;
}
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"fallback,無(wú)此流水,exception "+e.getMessage(),payment);
}
public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,無(wú)此流水: blockException "+blockException.getMessage(),payment);
}
}
配置sentinel

測(cè)試5
訪問(wèn)2次以后http://localhost:84/consumer/fallback/4

修改業(yè)務(wù)類(lèi)(fallback和blockHandler都配置)
@RestController
@Slf4j
public class CircleBreakerController
{
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler")
public CommonResult<Payment> fallback(@PathVariable Long id)
{
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("非法參數(shù)異常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,該ID沒(méi)有對(duì)應(yīng)記錄");
}
return result;
}
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"fallback,無(wú)此流水,exception "+e.getMessage(),payment);
}
public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,無(wú)此流水: blockException "+blockException.getMessage(),payment);
}
}

測(cè)試 6
訪問(wèn)http://localhost:84/consumer/fallback/4

再訪問(wèn)的時(shí)候,那就意味著這個(gè)時(shí)候會(huì)被限流處理

若 blockHandler 和 fallback 都進(jìn)行了配置,則被限流降級(jí)而拋出 BlockException 時(shí)只會(huì)進(jìn)入 blockHandler 處理邏輯。
修改業(yè)務(wù)類(lèi)(忽略屬性.......)
@RestController
@Slf4j
public class CircleBreakerController
{
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler",
exceptionsToIgnore = {IllegalArgumentException.class})
public CommonResult<Payment> fallback(@PathVariable Long id)
{
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("非法參數(shù)異常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,該ID沒(méi)有對(duì)應(yīng)記錄");
}
return result;
}
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"fallback,無(wú)此流水,exception "+e.getMessage(),payment);
}
public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,無(wú)此流水: blockException "+blockException.getMessage(),payment);
}
}
測(cè)試7
訪問(wèn)http://localhost:84/consumer/fallback/4

到此這篇關(guān)于sentinel整合ribbon與fallback流程分步講解的文章就介紹到這了,更多相關(guān)sentinel整合ribbon與fallback內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot如何統(tǒng)一處理返回結(jié)果和異常情況
這篇文章主要介紹了SpringBoot如何統(tǒng)一處理返回結(jié)果和異常情況問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
解決IntelliJ?IDEA輸出中文顯示為問(wèn)號(hào)問(wèn)題的有效方法
最近剛學(xué)到文件字節(jié)流這里,但輸出中文時(shí),出現(xiàn)了控制臺(tái)輸出問(wèn)號(hào)的情況,所以下面這篇文章主要給大家介紹了關(guān)于如何解決IntelliJ?IDEA輸出中文顯示為問(wèn)號(hào)問(wèn)題的有效方法,需要的朋友可以參考下2022-07-07
關(guān)于Java中增強(qiáng)for循環(huán)使用的注意事項(xiàng)
for循環(huán)語(yǔ)句是java循環(huán)語(yǔ)句中最常用的循環(huán)語(yǔ)句,一般用在循環(huán)次數(shù)已知的情況下使用,這篇文章主要給大家介紹了關(guān)于Java中增強(qiáng)for循環(huán)使用的注意事項(xiàng),需要的朋友可以參考下2021-06-06
Java實(shí)現(xiàn)遠(yuǎn)程控制技術(shù)完整源代碼分享
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)遠(yuǎn)程控制技術(shù)完整源代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
Junit 5中@ParameterizedTest與@EnumSource結(jié)合使用
今天小編就為大家分享一篇關(guān)于Junit 5中@ParameterizedTest與@EnumSource結(jié)合使用,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
Java實(shí)現(xiàn)解析.xlsb文件的示例代碼
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)解析.xlsb文件的相關(guān)方法,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的可以了解一下2023-01-01
Mybatis攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限的示例代碼
在我們?nèi)粘i_(kāi)發(fā)過(guò)程中,通常會(huì)涉及到數(shù)據(jù)權(quán)限問(wèn)題,本文主要介紹了Mybatis攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Mybatis詳解動(dòng)態(tài)SQL以及單表多表查詢的應(yīng)用
MyBatis的動(dòng)態(tài)SQL是基于OGNL表達(dá)式的,它可以幫助我們方便的在SQL語(yǔ)句中實(shí)現(xiàn)某些邏輯,下面這篇文章主要給大家介紹了關(guān)于Mybatis超級(jí)強(qiáng)大的動(dòng)態(tài)SQL語(yǔ)句的相關(guān)資料,需要的朋友可以參考下2022-06-06

