利用redis实现限流
需求,有些接口比较耗费资源,不可能支持用户无限制的调用,那么为了系统安全,需要拒绝某些用户请求。常见就是说一段时间内只能有多少请求。
排队,公交车。
区分这两个概念,排队,指的是,这个资源,只能由一个用户占有,常见需求就是说读写的时候,秒杀
他就是一个排队的概念,当前只有一个用户秒杀。
常见实现就是消息队列,分布式锁。
消息队列是异步,往往需要回调,听说12306就是一个异步的,你下单似乎是成功的,但是可能过段时间告诉你,抢票失败,为什么呢,因为12306的并发度太高了,如果用分布式锁,可能用户点来点去都是抢票失败,用户体验太差。
而公交车,其实就是一个限流的概念
在公交车来的时候,只能上这么一车人,塞不进去了。
也就是说,一段时间内,能占有资源的就是这么一票人。
常用于一些公共服务,比如说,一些调用系统资源的服务,系统资源是有限的,不可能无限调用,总要拒接掉一些请求,但是一个个来,对闲置资源又是极大的浪费。
比如调用第三方服务查询库存,太多会弄爆,太少又体验不好,所以限流。
实现思路
https://mp.weixin.qq.com/s/kyFAWH3mVNJvurQDt4vchA
https://www.cnblogs.com/use-D/p/9544903.html
https://www.cnblogs.com/huangqingshi/p/10290615.html
个人实现
我主要学习的还是利用第一种方法,方法进入时候计数,方法结束或异常时候,计数减1。
为了保证在操作redis的时候,操作是原子操作,所以利用了lua脚本进行判断。
@Configuration
public class RedisLimiterHelper {
@Bean
public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
声明一个redis的操作类,用于执行lua脚本。
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit {
/**
* 名字
*/
String name() default "";
/**
* key
*/
String key() default "";
/**
* Key的前缀
*/
String prefix() default "";
/**
* 给定的时间范围 单位(秒)
*/
int period() default -1;
/**
* 一定时间内最多访问次数
*/
int count();
/**
* 限流后返回描述
*/
String describle() default "当前系统繁忙,请稍后再试";
/**
* 限流的类型(用户自定义key或者请求ip)
*/
LimitType limitType() default LimitType.DEFAULT;
}
限流注解
public enum LimitType {
/**
* 自定义key
*/
CUSTOMER,
/**
* 默认key
*/
DEFAULT,
/**
* 请求者IP
*/
IP;
}
枚举类
@Aspect
@Configuration
@Slf4j
public class LimitAspect {
private static final String UNKNOWN = "unknown";
@Autowired
private RedisTemplate<String, Serializable> limitRedisTemplate;
//截获标有@CacheRemove的方法
@Pointcut(value = "(execution(public * *(..)) && @annotation(com.xy.microservice.common.annotation.Limit))")
private void pointcut() {
}
/**
* @param pjp
* @description 切面
* @date 2020/4/8 13:04
*/
@Around("pointcut()")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Limit limitAnnotation = method.getAnnotation(Limit.class);
LimitType limitType = limitAnnotation.limitType();
String name = limitAnnotation.name();
String key;
int limitPeriod = limitAnnotation.period();
int limitCount = limitAnnotation.count();
String describle=limitAnnotation.describle();
/**
* 根据限流类型获取不同的key ,如果不传我们会以方法名作为key
*/
switch (limitType) {
case IP:
key = getIpAddress();
break;
case CUSTOMER:
key = limitAnnotation.key();
break;
default:
key = StringUtils.upperCase(method.getName());
}
ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
try {
//如果有过期时间
if(limitPeriod>0){
String luaScript = buildIncrLuaScript();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
log.info("当前方法内已有数量 is {} for 名称为={} and key = {}", count, name, key);
if (count != null && count.intValue() <= limitCount) {
return pjp.proceed();
} else {
throw new RuntimeException(describle);
}
}else{
String luaScript = buildIncrLuaScriptNoExpire();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount);
log.info("当前方法内已有数量 is {} for 名称为={} and key = {}", count, name, key);
if (count != null && count.intValue() <= limitCount) {
return pjp.proceed();
} else {
throw new RuntimeException(describle);
}
}
} catch (Throwable e) {
if (e instanceof RuntimeException) {
throw new RuntimeException(e.getLocalizedMessage());
}
throw new RuntimeException("server exception");
}
}
/**
* 功能描述: 切面在截获方法返回值之后
*
*/
@AfterReturning(value = "pointcut()")
private void process(JoinPoint joinPoint) throws BusinessException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Limit limitAnnotation = method.getAnnotation(Limit.class);
LimitType limitType = limitAnnotation.limitType();
String name = limitAnnotation.name();
String key;
int limitPeriod = limitAnnotation.period();
int limitCount = limitAnnotation.count();
String describle=limitAnnotation.describle();
/**
* 根据限流类型获取不同的key ,如果不传我们会以方法名作为key
*/
switch (limitType) {
case IP:
key = getIpAddress();
break;
case CUSTOMER:
key = limitAnnotation.key();
break;
default:
key = StringUtils.upperCase(method.getName());
}
ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
try {
if(limitPeriod>0){
String luaScript = buildDecrLuaScript();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount);
log.info("结束后当前方法内数量为 {} for 名称为={} and key = {}", count, name, key);
}else{
String luaScript = buildDecrLuaScriptNoExpire();
RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
Number count = limitRedisTemplate.execute(redisScript, keys, limitCount);
log.info("结束后当前方法内数量为 {} for 名称为={} and key = {}", count, name, key);
}
} catch (Throwable e) {
throw new BusinessException("server exception");
}
}
/**
* @description 编写Redis 进入函数的计数限流脚本
*/
public String buildIncrLuaScript() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nc = redis.call('get',KEYS[1])");
// 调用超过最大值,则直接返回
lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
lua.append("\nreturn c;");
lua.append("\nend");
// 执行计算器自加
lua.append("\nc = redis.call('incr',KEYS[1])");
lua.append("\nif tonumber(c) == 1 then");
// 从第一次调用开始限流,设置对应键值的过期
lua.append("\nredis.call('expire',KEYS[1],ARGV[2])");
lua.append("\nend");
lua.append("\nreturn c;");
return lua.toString();
}
/**
* @description 编写Redis 进入函数的计数限流脚本无过期时间
*/
public String buildIncrLuaScriptNoExpire() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nc = redis.call('get',KEYS[1])");
// 调用超过最大值,则直接返回
lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
lua.append("\nreturn c;");
lua.append("\nend");
// 执行计算器自加
lua.append("\nc = redis.call('incr',KEYS[1])");
lua.append("\nreturn c;");
return lua.toString();
}
/**
* @description 编写Redis 结束函数的减数限流脚本
*/
public String buildDecrLuaScript() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nlocal ttl");
lua.append("\nc = redis.call('get',KEYS[1])");
lua.append("\nttl = redis.call('ttl',KEYS[1])");
// 调用不超过最大值,则直接返回
lua.append("\nif c then");
lua.append("\n c=redis.call('decr',KEYS[1])");
lua.append("\n redis.call('expire',KEYS[1],ttl)");
lua.append("\nreturn c;");
lua.append("\nend");
return lua.toString();
}
/**
* @description 编写Redis 结束函数的减数限流脚本无过期时间
*/
public String buildDecrLuaScriptNoExpire() {
StringBuilder lua = new StringBuilder();
lua.append("local c");
lua.append("\nc = redis.call('get',KEYS[1])");
// 调用不超过最大值,则直接返回
lua.append("\nif c then");
lua.append("\n c=redis.call('decr',KEYS[1])");
lua.append("\nreturn c;");
lua.append("\nend");
return lua.toString();
}
/**
* @author fu
* @description 获取id地址
* @date 2020/4/8 13:24
*/
public String getIpAddress() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
切面,主要操作就是在方法进入时候,在声明的key里redis里加一,如果超过限定数量,直接抛出异常。然后我添加了在方法不管是正常接收还是异常结束,都redis减一。
主要学习的还是redis的lua脚本执行方法