SpringCloud Alibaba Sentinel限流熔断降级--------------客户端配置熔断降级
前面的文章介绍了配置客户端,实现接口限流。但是在实际应用中,当我们的某个服务接口出现了问题,不能正常提供服务,或者该接口响应速度很慢,导致调用方大量请求堆积,此时需要将该接口降级服务,从而保护调用该接口的服务,快速返回降级结果,防止因为过多的服务等待该接口的返回,导致系统雪崩。本文介绍通过sentinel实现接口熔断降级。
控制台的启动不再赘述,可以看之前的博客介绍https://blog.****.net/qq_26932225/article/details/88907123,下面直接介绍客户端的配置。本文代码地址:https://github.com/xujingle1995/Learn-SpringCloudAlibaba/tree/master/sentinel-client-fallback
引入依赖
<!-- Sentinel -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.2.1.RELEASE</version>
</dependency>
配置文件
spring.cloud.sentinel.transport.port=8731
spring.cloud.sentinel.transport.dashboard=localhost:8080
server.port=8090
spring.application.name=sentinel-client-fallback
添加代码
Controller层
package com.xjl.sentinel.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.xjl.sentinel.service.FallbackService;
@RestController
public class SentinelTestController {
@Autowired
private FallbackService service;
@GetMapping("/getName/{name}")
public String getName(@PathVariable("name") String name) throws InterruptedException, DegradeException {
System.out.println(name);
return service.getName(name);
}
}
Service层
package com.xjl.sentinel.service;
public interface FallbackService {
public String getName(String name) throws InterruptedException;
}
Service实现层
package com.xjl.sentinel.service.impl;
import org.springframework.stereotype.Service;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.xjl.sentinel.service.FallbackService;
@Service
public class FallbackServiceImpl implements FallbackService {
@Override
@SentinelResource(value = "getName", fallback = "getNameFallback")
public String getName(String name) {
// 为了使返回时间按比较长
for (int i = 0; i < 100000000L; i++) {
}
return "getName " + name;
}
// 该方法降级处理函数,参数要与原函数getName相同,并且返回值类型也要与原函数相同,此外,该方法必须与原函数在同一个类中
public String getNameFallback(String name){
return "getNameFallback";
}
}
启动控制台、客户端
请求一次接口http://localhost:8090/getName/xjl,在控制台就可以看到该应用。
控制台添加降级规则
根据响应时间,大于10毫秒,则熔断降级(要连续超过5个请求超过10毫秒才会熔断)
Jmeter测试
测试异常熔断降级
修改service 实现层代码
@Service
public class FallbackServiceImpl implements FallbackService {
@Override
@SentinelResource(value = "getName", fallback = "getNameFallback")
public String getName(String name) {
for (int i = 0; i < 100000000L; i++) {
throw new RuntimeException();
}
return "getName " + name;
}
public String getNameFallback(String name){
return "getNameFallback";
}
}
修改控制台降级规则
jmeter测试:显示抛出是10个异常,然后返回结果是熔断处理方法返回结果
客户端代码地址
https://github.com/xujingle1995/Learn-SpringCloudAlibaba/tree/master/sentinel-client-fallback