站酷网页设计分析,微信公众号如何创建视频链接,ae免费模板网站,网站开发布局文章目录 Redis Lua 限流实现1. 导入依赖2. 配置application.properties3. 配置RedisTemplate实例4. 定义限流类型枚举类5. 自定义注解6. 切面代码实现7. 控制层实现8. 测试 相比
Redis事务#xff0c;
Lua脚本的优点#xff1a; 减少网络开销#xff1a;使用Lua脚本 Lua 限流实现1. 导入依赖2. 配置application.properties3. 配置RedisTemplate实例4. 定义限流类型枚举类5. 自定义注解6. 切面代码实现7. 控制层实现8. 测试 相比
Redis事务
Lua脚本的优点 减少网络开销使用Lua脚本无需向Redis 发送多次请求执行一次即可减少网络传输原子操作Redis 将整个Lua脚本作为一个命令执行原子无需担心并发复用Lua脚本一旦执行会永久保存 Redis 中,其他客户端可复用
Redis Lua 限流实现
技术栈自定义注解、aop、Redis Lua 实现限流
1. 导入依赖 dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId/dependencydependencygroupIdorg.apache.commons/groupIdartifactIdcommons-lang3/artifactId/dependencydependencygroupIdcom.google.guava/groupIdartifactIdguava/artifactIdversion30.1-jre/version/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency/dependencies2. 配置application.properties
spring.redis.host10.1.61.121
spring.redis.port6379
spring.redis.password1234563. 配置RedisTemplate实例
package com.lihw.lihwtestboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;Configuration
public class RedisLimiterHelper {Beanpublic RedisTemplateString, Serializable limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {RedisTemplateString, Serializable template new RedisTemplate();template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}
}4. 定义限流类型枚举类
package com.lihw.lihwtestboot.schemas;/*** explain: 限流类型* author: lihewei
*/
public enum LimitType {/*** 自定义key*/CUSTOMER,/*** 请求者IP*/IP;
}5. 自定义注解
period表示请求限制时间段count表示在period这个时间段内允许放行请求的次数。limitType代表限流的类型可以根据请求的IP、自定义key如果不传limitType属性则默认用方法名作为默认key。
package com.lihw.lihwtestboot.anno;
import com.lihw.lihwtestboot.schemas.LimitType;
import java.lang.annotation.*;/*** explain: 自定义限流注解* author: lihewei
*/
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();/*** 一定时间内最多访问次数*/int count();/*** 限流的类型(用户自定义key 或者 请求ip)*/LimitType limitType() default LimitType.CUSTOMER;
}6. 切面代码实现
package com.lihw.lihwtestboot.aop;
import com.google.common.collect.ImmutableList;
import com.lihw.lihwtestboot.anno.Limit;
import com.lihw.lihwtestboot.schemas.LimitType;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;/*** explain: 限流切面实现* author: lihewei
*/
Aspect
Configuration
public class LimitInterceptor {private static final Logger logger LoggerFactory.getLogger(LimitInterceptor.class);private static final String UNKNOWN unknown;private final RedisTemplateString, Serializable limitRedisTemplate;Autowiredpublic LimitInterceptor(RedisTemplateString, Serializable limitRedisTemplate) {this.limitRedisTemplate limitRedisTemplate;}/*** author lihw* description 切面*/Around(execution(public * *(..)) annotation(com.lihw.lihwtestboot.anno.Limit))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();/*** 根据限流类型获取不同的key ,如果不传我们会以方法名作为key*/switch (limitType) {case IP:key getIpAddress();break;case CUSTOMER:key limitAnnotation.key();break;default:key StringUtils.upperCase(method.getName());}ImmutableListString keys ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));try {String luaScript buildLuaScript();RedisScriptNumber redisScript new DefaultRedisScript(luaScript, Number.class);Number count limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);logger.info(Access try count is {} for name{} and key {}, count, name, key);if (count ! null count.intValue() limitCount) {return pjp.proceed();} else {throw new RuntimeException(You have been dragged into the blacklist);}} catch (Throwable e) {if (e instanceof RuntimeException) {throw new RuntimeException(e.getLocalizedMessage());}throw new RuntimeException(server exception);}}/*** description 编写 redis Lua 限流脚本*/public String buildLuaScript() {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 获取id地址*/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;}
}7. 控制层实现
package com.lihw.lihwtestboot.controller;import com.lihw.lihwtestboot.anno.Limit;
import com.lihw.lihwtestboot.schemas.LimitType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicInteger;RestController
public class LimiterController {private static final AtomicInteger ATOMIC_INTEGER_1 new AtomicInteger();private static final AtomicInteger ATOMIC_INTEGER_2 new AtomicInteger();private static final AtomicInteger ATOMIC_INTEGER_3 new AtomicInteger();Limit(key limitTest, period 10, count 3)GetMapping(/limitTest1)public int testLimiter1() {return ATOMIC_INTEGER_1.incrementAndGet();}Limit(key customer_limit_test, period 10, count 3, limitType LimitType.CUSTOMER)GetMapping(/limitTest2)public int testLimiter2() {return ATOMIC_INTEGER_2.incrementAndGet();}Limit(key ip_limit_test, period 10, count 3, limitType LimitType.IP)GetMapping(/limitTest3)public int testLimiter3() {return ATOMIC_INTEGER_3.incrementAndGet();}
}8. 测试 10s内连续请求三次以上拒绝请求
文章转载自: http://www.morning.yltyr.cn.gov.cn.yltyr.cn http://www.morning.hcxhz.cn.gov.cn.hcxhz.cn http://www.morning.zrgdd.cn.gov.cn.zrgdd.cn http://www.morning.gczqt.cn.gov.cn.gczqt.cn http://www.morning.snrhg.cn.gov.cn.snrhg.cn http://www.morning.sjmxh.cn.gov.cn.sjmxh.cn http://www.morning.glpxx.cn.gov.cn.glpxx.cn http://www.morning.rkwlg.cn.gov.cn.rkwlg.cn http://www.morning.bwttp.cn.gov.cn.bwttp.cn http://www.morning.txlxr.cn.gov.cn.txlxr.cn http://www.morning.srbl.cn.gov.cn.srbl.cn http://www.morning.ssgqc.cn.gov.cn.ssgqc.cn http://www.morning.cwwbm.cn.gov.cn.cwwbm.cn http://www.morning.jkwwm.cn.gov.cn.jkwwm.cn http://www.morning.wjhpg.cn.gov.cn.wjhpg.cn http://www.morning.lznfl.cn.gov.cn.lznfl.cn http://www.morning.hrhwn.cn.gov.cn.hrhwn.cn http://www.morning.rdfq.cn.gov.cn.rdfq.cn http://www.morning.wpcfh.cn.gov.cn.wpcfh.cn http://www.morning.tbqxh.cn.gov.cn.tbqxh.cn http://www.morning.rdnpg.cn.gov.cn.rdnpg.cn http://www.morning.fyskq.cn.gov.cn.fyskq.cn http://www.morning.prgnp.cn.gov.cn.prgnp.cn http://www.morning.qbgdy.cn.gov.cn.qbgdy.cn http://www.morning.bwznl.cn.gov.cn.bwznl.cn http://www.morning.zdkzj.cn.gov.cn.zdkzj.cn http://www.morning.rnmc.cn.gov.cn.rnmc.cn http://www.morning.cfcdr.cn.gov.cn.cfcdr.cn http://www.morning.rjyd.cn.gov.cn.rjyd.cn http://www.morning.fgkwh.cn.gov.cn.fgkwh.cn http://www.morning.ljdjn.cn.gov.cn.ljdjn.cn http://www.morning.rqhn.cn.gov.cn.rqhn.cn http://www.morning.lsgjf.cn.gov.cn.lsgjf.cn http://www.morning.trpq.cn.gov.cn.trpq.cn http://www.morning.rzbcz.cn.gov.cn.rzbcz.cn http://www.morning.fxpyt.cn.gov.cn.fxpyt.cn http://www.morning.xkzr.cn.gov.cn.xkzr.cn http://www.morning.xmhpq.cn.gov.cn.xmhpq.cn http://www.morning.fpxms.cn.gov.cn.fpxms.cn http://www.morning.qrmyd.cn.gov.cn.qrmyd.cn http://www.morning.wddmr.cn.gov.cn.wddmr.cn http://www.morning.zrkws.cn.gov.cn.zrkws.cn http://www.morning.zypnt.cn.gov.cn.zypnt.cn http://www.morning.ztmkg.cn.gov.cn.ztmkg.cn http://www.morning.jhrqn.cn.gov.cn.jhrqn.cn http://www.morning.tfqfm.cn.gov.cn.tfqfm.cn http://www.morning.rmmz.cn.gov.cn.rmmz.cn http://www.morning.qgjwx.cn.gov.cn.qgjwx.cn http://www.morning.sgjw.cn.gov.cn.sgjw.cn http://www.morning.zfqr.cn.gov.cn.zfqr.cn http://www.morning.prddj.cn.gov.cn.prddj.cn http://www.morning.gcfg.cn.gov.cn.gcfg.cn http://www.morning.hxmqb.cn.gov.cn.hxmqb.cn http://www.morning.gpnfg.cn.gov.cn.gpnfg.cn http://www.morning.qyllw.cn.gov.cn.qyllw.cn http://www.morning.xnzmc.cn.gov.cn.xnzmc.cn http://www.morning.rsjf.cn.gov.cn.rsjf.cn http://www.morning.c7493.cn.gov.cn.c7493.cn http://www.morning.wwklf.cn.gov.cn.wwklf.cn http://www.morning.rksnk.cn.gov.cn.rksnk.cn http://www.morning.jcwhk.cn.gov.cn.jcwhk.cn http://www.morning.ptxwg.cn.gov.cn.ptxwg.cn http://www.morning.fnczn.cn.gov.cn.fnczn.cn http://www.morning.tllws.cn.gov.cn.tllws.cn http://www.morning.dnconr.cn.gov.cn.dnconr.cn http://www.morning.pmsl.cn.gov.cn.pmsl.cn http://www.morning.xyjlh.cn.gov.cn.xyjlh.cn http://www.morning.jqhrk.cn.gov.cn.jqhrk.cn http://www.morning.zthln.cn.gov.cn.zthln.cn http://www.morning.rxlk.cn.gov.cn.rxlk.cn http://www.morning.mtymb.cn.gov.cn.mtymb.cn http://www.morning.lzqtn.cn.gov.cn.lzqtn.cn http://www.morning.ktrh.cn.gov.cn.ktrh.cn http://www.morning.kwpnx.cn.gov.cn.kwpnx.cn http://www.morning.kqqk.cn.gov.cn.kqqk.cn http://www.morning.nzdks.cn.gov.cn.nzdks.cn http://www.morning.gtbjc.cn.gov.cn.gtbjc.cn http://www.morning.pmmrb.cn.gov.cn.pmmrb.cn http://www.morning.fjfjm.cn.gov.cn.fjfjm.cn http://www.morning.tdmr.cn.gov.cn.tdmr.cn