什么是==熔断==
当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,**进而熔断该节点微服务的调用,快速返回错误的响应信息。**检测到该节点微服务调用响应正常后恢复调用链路。
A服务调用 B服务的某个功能,由于网络不稳定问题,或者 B服务卡机,导致功能时间超长。如果这样的次数很多。我们就可以直接将 B服务段路了(A不再请求 B接口),凡是调用 B得直接返回降级数据,不必等待 B的超长执行。这样 B的故障问题,就不会级联影响到 A服务。
什么是**降级**
什么是**限流**
熔断和降级异同:
sentinel的基础知识参考:https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D
简介:
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。
Sentinel 分为两个部分:
官方文档
第一步、在gulimall-common 服务中 导入依赖
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
第二步、去官网下载项目里sentinel对应的版本的控制台官网下载
1、在路径下执行
hgw@HGWdeAir SpringCloudSentinel# java -jar sentinel-dashboard-1.6.3.jar --server.port=8333
2、访问http://localhost:8333/
用户名:sentinel
密码:sentinel
第三步、配置Sentinel
在gulimall-seckill 服务的配置文件中:
#sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8333
#sentinel传输端口
spring.cloud.sentinel.transport.port=8713
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
package com.atguigu.gulimall.seckill.config;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Data time:2022/4/18 11:33
* StudentID:2019112118
* Author:hgw
* Description: Sentinel-自定义流控响应
*/
@Configuration
public class SeckillSentinelConfig {
public SeckillSentinelConfig() {
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
R error = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMsg());
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().write(JSON.toJSONString(error));
}
});
}
}
1、为每个服务引入 actuator依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
2、配置 sentinel
#sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8333
management.endpoints.web.exposure.include=*
1)、调用方的熔断保护开启 feign.sentinel.enabled=true
2)、调用方手动指定远程服务的降级策略。远程服务被降级处理,触发我们的熔断回调方法
3)、超大浏览的时候,必须牺牲一些远程服务。在服务的提供方(远程服务)指定降级策略; 提供方是在运行。但是不运行自己的业务逻辑。返回的是默认的降级数据(限流的数据)
默认情况下,sentinel是不会对feign进行监控的,需要开启配置
在gulimall-product类配置文件添加配置
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true
使用Sentinel来保护feign远程调用:熔断。举一个案例:
1、在gulimall-product类配置文件添加配置
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true
2、编写 熔断回调方法
package com.atguigu.gulimall.product.feign.fallback;
@Slf4j
@Component
public class SeckillFeignServiceFallBack implements SeckillFeignService {
@Override
public R getSkuSeckillInfo(Long skuId) {
log.error("熔断方法调用...getSkuSeckillInfo");
return R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(),BizCodeEnume.TO_MANY_REQUEST.getMsg());
}
}
3、指定 服务熔断回调方法@FeignClient(fallback = 指定的熔断回调方法)
package com.atguigu.gulimall.product.feign;
@FeignClient(value = "gulimall-seckill", fallback = SeckillFeignServiceFallBack.class)
public interface SeckillFeignService {
@GetMapping("/sku/seckill/{skuId}")
R getSkuSeckillInfo(@PathVariable("skuId") Long skuId);
}
设置调用降级:
* 5、自定义受保护资源
* 1、基于代码的 自定义受保护资源
* try(Entry entity = SphU.entry("自定义受保护资源名")) {
* // 业务逻辑
* } catch (BlockException e) {
* //一定要配置被限流以后的默认返回
* }
* 2、基于注解
* @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
* 无论是1、2方式一定要配置被限流以后的默认返回。
* url请求可以设置统一返回:WebCallbackManager
try(Entry entity = SphU.entry("自定义受保护资源名")) {
// 业务逻辑
} catch (BlockException e) {
//一定要配置被限流以后的默认返回
}
1、编写自定义受保护资源
修改“com.atguigu.gulimall.seckill.service.impl.SeckillServiceImpl”类 代码如下:
/**
* 获取当前参与秒杀的商品
*
* @return
*/
@Override
public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
try(Entry entity = SphU.entry("seckillSkus")) {
// 1、确定当前时间属于哪个秒杀场次
long time = new Date().getTime();
Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
for (String key : keys) {
// seckill:sessions:1650153600000_1650160800000
String replace = key.replace(SESSION_CACHE_PREFIX, "");
String[] s = replace.split("_");
long start = Long.parseLong(s[0]);
long end = Long.parseLong(s[1]);
if (time >= start && time <= end) {
// 2、获取指定秒杀场次需要的所有商品信息
List<String> range = redisTemplate.opsForList().range(key, -100, 100);
BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
List<String> list = hashOps.multiGet(range);
if (list != null) {
List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
SecKillSkuRedisTo redis = JSON.parseObject((String) item, SecKillSkuRedisTo.class);
redis.setRandomCode(null); // 当前秒杀开始了需要随机码
return redis;
}).collect(Collectors.toList());
return collect;
}
break;
}
}
} catch (BlockException e) {
log.error("资源被限流{}"+e.getMessage());
}
return null;
}
可以为自定义的受保护资源 加上流控、降级。
@SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler",fallback = "fallback")
/**
* getCurrentSeckillSkus()方法被限流/降级/系统保护的时候调用
* @return
*/
public List<SecKillSkuRedisTo> blockHandler(BlockException e){
log.error("getCurrentSeckillSkus()方法被限流/降级/系统保护");
return null;
}
/**
* 获取当前参与秒杀的商品
* blockHandler 函数会在原方法被限流/降级/系统保护的时候调用
* fallback 会针对所有类型的异常
* @return
*/
@SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
@Override
public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
try(Entry entity = SphU.entry("seckillSkus")) {
// 1、确定当前时间属于哪个秒杀场次
long time = new Date().getTime();
Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
for (String key : keys) {
// seckill:sessions:1650153600000_1650160800000
String replace = key.replace(SESSION_CACHE_PREFIX, "");
String[] s = replace.split("_");
long start = Long.parseLong(s[0]);
long end = Long.parseLong(s[1]);
if (time >= start && time <= end) {
// 2、获取指定秒杀场次需要的所有商品信息
List<String> range = redisTemplate.opsForList().range(key, -100, 100);
BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
List<String> list = hashOps.multiGet(range);
if (list != null) {
List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
SecKillSkuRedisTo redis = JSON.parseObject((String) item, SecKillSkuRedisTo.class);
redis.setRandomCode(null); // 当前秒杀开始了需要随机码
return redis;
}).collect(Collectors.toList());
return collect;
}
break;
}
}
} catch (BlockException e) {
log.error("资源被限流{}"+e.getMessage());
}
return null;
}
如果能在网关层就进行流控,可以避免请求流入业务,减小服务压力
1、gulimall-gateway引入依赖
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-alibaba-sentinel-gatewayartifactId>
<version>2.1.0.RELEASEversion>
dependency>
注意引入的依赖要和gulimall-common的pom里的阿里巴巴版本一致
2、配置流控
API 名称就是: 网关中配置路由名
比如说指定请求头被限流:
3、自定义网关流控返回
package com.atguigu.gulimall.gateway.config;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.netflix.loadbalancer.Server;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Data time:2022/4/18 17:21
* StudentID:2019112118
* Author:hgw
* Description:
*/
@Configuration
public class SentinelGatewayConfig {
public SentinelGatewayConfig() {
GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
// 网关限制了请求,就会调用此回调 Mono Flux
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
R error = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMsg());
String errJson = JSON.toJSONString(error);
Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errJson), String.class);
return body;
}
});
}
}