目录
[Sentinel 的QPS限流](#Sentinel 的QPS限流)
[在代码中引入 Sentinel 注解控制流控规则。](#在代码中引入 Sentinel 注解控制流控规则。)
配置过滤器器执行lua脚本,判断访问次数是否超过:我们可以通过这个过滤器得知,再timeWindow时间内,我们的访问次数是否超过设定的currentAccessCount
Sentinel 的QPS限流
导入依赖:
java
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
</dependency>
这个限制的时每秒的QPS为1:
java
/**
* 初始化限流配置
*
*/
@Component
public class SentinelRuleConfig implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
List<FlowRule> rules = new ArrayList<>();
FlowRule createOrderRule = new FlowRule();
createOrderRule.setResource("create_short-link");
createOrderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
createOrderRule.setCount(1);
rules.add(createOrderRule);
FlowRuleManager.loadRules(rules);
}
}
如果触发风控,设置降级策略。
java
/**
* 自定义流控策略
*
*/
public class CustomBlockHandler {
public static Result<ShortLinkCreateRespDTO> createShortLinkBlockHandlerMethod(ShortLinkCreateReqDTO requestParam, BlockException exception) {
return new Result<ShortLinkCreateRespDTO>().setCode("B100000").setMessage("当前访问网站人数过多,请稍后再试...");
}
}
在代码中引入 Sentinel 注解控制流控规则。
java
/**
* 创建XXX
*/
@PostMapping("/api/short-link/v1/create")
@SentinelResource(
value = "create_short-link",
blockHandler = "createShortLinkBlockHandlerMethod",
blockHandlerClass = CustomBlockHandler.class
)
public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreateReqDTO requestParam) {
return Results.success(shortLinkService.createShortLink(requestParam));
}
限制了每秒钟只能有一个创建XXX的请求被成功处理。多余的请求在该时间段内会被限流处理(如返回错误信息、等待、丢弃等),直到下一秒开始重新计数。这样可以防止短时间内大量请求对服务端造成压力,保证系统的稳定性和可用性。
用Redis实现流量风控:
用redis的自增,key不存在,设置值为1,每次访问加1。
有效期是timeWindow,访问次数是currentAccessCount
lua脚本如下:
Lua
-- 设置用户访问频率限制的参数
local username = KEYS[1]
local timeWindow = tonumber(ARGV[1]) -- 时间窗口,单位:秒
-- 构造 Redis 中存储用户访问次数的键名
local accessKey = "short-link:user-flow-risk-control:" .. username
-- 原子递增访问次数,并获取递增后的值
local currentAccessCount = redis.call("INCR", accessKey)
-- 设置键的过期时间
redis.call("EXPIRE", accessKey, timeWindow)
-- 返回当前访问次数
return currentAccessCount
配置过滤器器执行lua脚本,判断访问次数是否超过:
我们可以通过这个过滤器得知,再timeWindow时间内,我们的访问次数是否超过设定的currentAccessCount
java
/**
* 用户操作流量分控过滤器
*/
@Slf4j
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {
private final StringRedisTemplate stringRedisTemplate;
private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;
private static final String USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";
@SneakyThrows
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
// lua脚本执行 魔板
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//lua脚本执 路径
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH)));
//返回值结果类型
redisScript.setResultType(Long.class);
String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");
Long result;
try {
result = stringRedisTemplate.execute(redisScript, Lists.newArrayList(username), userFlowRiskControlConfiguration.getTimeWindow());
} catch (Throwable ex) {
log.error("执行用户请求流量限制LUA脚本出错", ex);
returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
return;
}
if (result == null || result > userFlowRiskControlConfiguration.getMaxAccessCount()) {
returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
return;
}
filterChain.doFilter(request, response);
}
private void returnJson(HttpServletResponse response, String json) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try (PrintWriter writer = response.getWriter()) {
writer.print(json);
}
}
}
然后配置过滤器使其生效:
java
package com.wyk.config;
import com.wyk.common.biz.user.UserFlowRiskControlFilter;
import com.wyk.common.biz.user.UserTransmitFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
/**
* 用户配置自动装配
*/
@Configuration
public class UserConfiguration {
/**
* 用户操作流量风控过滤器
*/
@Bean
@ConditionalOnProperty(name = "short-link.flow-limit.enable", havingValue = "true")
public FilterRegistrationBean<UserFlowRiskControlFilter> globalUserFlowRiskControlFilter(
StringRedisTemplate stringRedisTemplate,
UserFlowRiskControlConfiguration userFlowRiskControlConfiguration) {
FilterRegistrationBean<UserFlowRiskControlFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new UserFlowRiskControlFilter(stringRedisTemplate, userFlowRiskControlConfiguration));
registration.addUrlPatterns("/*");
registration.setOrder(10);
return registration;
}
}
下面是针对上面的一些参数的配置读取
java
@Data
@Component
@ConfigurationProperties(prefix = "short-link.flow-limit")
public class UserFlowRiskControlConfiguration {
/**
* 是否开启用户流量风控验证
*/
private Boolean enable;
/**
* 流量风控时间窗口,单位:秒
*/
private String timeWindow;
/**
* 流量风控时间窗口内可访问次数
*/
private Long maxAccessCount;
}
yaml里面配置风控的参数
java
short-link:
flow-limit:
enable: true
time-window: 1
max-access-count: 20