1987WEB视界-分享互联网热点话题和事件

您现在的位置是:首页 > WEB开发 > 正文

WEB开发

借助redis实现对IP限流

1987web2024-03-27WEB开发34
背景:若依前后端分离项目(vue+springboot+springmvc+mybatis),redis。

背景:
若依前后端分离项目(vue+springboot+springmvc+mybatis),redis。
需求:
借助redis实现对IP限流。
实现:
参考
https://blog.csdn.net/qq_33762302/article/details/116258617
代码如下:
IPLimiter.java 定义注解类,将注解定义在需要分流IP的接口上
1importjava.lang.annotation.*;23@Target(ElementType.METHOD)4@Retention(RetentionPolicy.RUNTIME)5@Documented6public@interfaceIpLimiter{7/**8* 放行ip9*/10String[]ipAdress()default{""};11/**12* 单位时间限制通过请求数13*/14longlimit()default10;15/**16* 单位时间,单位秒17*/18longtime()default1;19/**20* 达到限流提示语21*/22Stringmessage();2324/**25* 是否锁住IP的同时锁住URI26*/27booleanlockUri()defaultfalse;28}

IpLimterHandler.java 注解AOP处理。

1importcom.missionex.common.annotation.IpLimiter;2importcom.missionex.common.core.domain.AjaxResult;3importcom.missionex.common.utils.DateUtils;4importcom.missionex.common.utils.SecurityUtils;5importcom.missionex.common.utils.http.IPAddressUtils;6importorg.aspectj.lang.ProceedingJoinPoint;7importorg.aspectj.lang.Signature;8importorg.aspectj.lang.annotation.Around;9importorg.aspectj.lang.annotation.Aspect;10importorg.aspectj.lang.reflect.MethodSignature;11importorg.slf4j.Logger;12importorg.slf4j.LoggerFactory;13importorg.springframework.beans.factory.annotation.Autowired;14importorg.springframework.core.io.ClassPathResource;15importorg.springframework.data.redis.core.StringRedisTemplate;16importorg.springframework.data.redis.core.script.DefaultRedisScript;17importorg.springframework.scripting.support.ResourceScriptSource;18importorg.springframework.stereotype.Component;19importorg.springframework.web.context.request.RequestContextHolder;20importorg.springframework.web.context.request.ServletRequestAttributes;2122importjavax.annotation.PostConstruct;23importjavax.servlet.http.HttpServletRequest;24importjava.util.ArrayList;25importjava.util.List;2627@Aspect28@Component29publicclassIpLimterHandler{3031privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger("request-limit");3233@Autowired34StringRedisTemplateredisTemplate;353637/**38* getRedisScript 读取脚本工具类39* 这里设置为Long,是因为ipLimiter.lua 脚本返回的是数字类型40*/41privateDefaultRedisScript<Long>getRedisScript;4243@PostConstruct44publicvoidinit(){45getRedisScript=newDefaultRedisScript<>();46getRedisScript.setResultType(Long.class);47getRedisScript.setScriptSource(newResourceScriptSource(newClassPathResource("ipLimiter.lua")));48LOGGER.info("IpLimterHandler[分布式限流处理器]脚本加载完成");49}5051/**52* 这个切点可以不要,因为下面的本身就是个注解53*/54//@Pointcut("@annotation(com.jincou.iplimiter.annotation.IpLimiter)")55//public void rateLimiter() {}5657/**58* 如果保留上面这个切点,那么这里可以写成59* @Around("rateLimiter()&&@annotation(ipLimiter)")60*/61@Around("@annotation(ipLimiter)")62publicObjectaround(ProceedingJoinPointproceedingJoinPoint,IpLimiteripLimiter)throwsThrowable{63if(LOGGER.isDebugEnabled()){64LOGGER.debug("IpLimterHandler[分布式限流处理器]开始执行限流操作");65}66StringuserIp=null;67StringrequestURI=null;68try{69//获取请求信息70HttpServletRequestrequest=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();71requestURI=request.getRequestURI();72StringrequestMethod=request.getMethod();73StringremoteAddr=request.getRemoteAddr();74//获取请求用户IP75userIp=IPAddressUtils.getIpAdrress(request);76if(userIp==null){77returnAjaxResult.error("运行环境存在风险");78}79}catch(Exceptione){80LOGGER.error("获取request出错=>"+e.getMessage());81if(userIp==null){82returnAjaxResult.error("运行环境存在风险");83}84}85Signaturesignature=proceedingJoinPoint.getSignature();86if(!(signatureinstanceofMethodSignature)){87thrownewIllegalArgumentException("the Annotation @IpLimter must used on method!");88}89/**90* 获取注解参数91*/92//放行模块IP93String[]limitIp=ipLimiter.ipAdress();94intlen;95if(limitIp!=null&&(len=limitIp.length)!=0){96for(inti=0;i<len;i++){97if(limitIp[i].equals(userIp)){98returnproceedingJoinPoint.proceed();99}100}101}102//限流阈值103longlimitTimes=ipLimiter.limit();104//限流超时时间105longexpireTime=ipLimiter.time();106booleanlockUri=ipLimiter.lockUri();107if(LOGGER.isDebugEnabled()){108LOGGER.debug("IpLimterHandler[分布式限流处理器]参数值为-limitTimes={},limitTimeout={}",limitTimes,expireTime);109}110//限流提示语111Stringmessage=ipLimiter.message();112/**113* 执行Lua脚本114*/115List<String>ipList=newArrayList();116//设置key值为注解中的值117if(lockUri){118ipList.add(userIp+requestURI);119}else{120ipList.add(userIp);121}122/**123* 调用脚本并执行124*/125try{126Objectx=redisTemplate.execute(getRedisScript,ipList,expireTime+"",limitTimes+"");127Longresult=(Long)x;128if(result==0){129LonguserId=null;130try{131userId=SecurityUtils.getLoginUser().getAppUser().getId();132}catch(Exceptione){133134}135LOGGER.info("[分布式限流处理器]限流执行结果-ip={}-接口={}-用户ID={}-result={}-time={},已被限流",userIp,requestURI==null?"未知":requestURI136,userId==null?"用户未登录":userId,result,DateUtils.getTime());137//达到限流返回给前端信息138returnAjaxResult.error(message);139}140if(LOGGER.isDebugEnabled()){141LOGGER.debug("IpLimterHandler[分布式限流处理器]限流执行结果-result={},请求[正常]响应",result);142}143returnproceedingJoinPoint.proceed();144}catch(Exceptione){145LOGGER.error("限流错误",e);146returnproceedingJoinPoint.proceed();147}148149}150}

ipLimiter.lua 脚本,放在resources文件夹中。

1-获取KEY2localkey1=KEYS[1]34localval=redis.call(incr,key1)5localttl=redis.call(ttl,key1)67--获取ARGV内的参数并打印8localexpire=ARGV[1]9localtimes=ARGV[2]1011redis.log(redis.LOG_DEBUG,tostring(times))12redis.log(redis.LOG_DEBUG,tostring(expire))1314redis.log(redis.LOG_NOTICE,"incr "..key1.." "..val);15ifval==1then16redis.call(expire,key1,tonumber(expire))17else18ifttl==-1then19redis.call(expire,key1,tonumber(expire))20end21end2223ifval>tonumber(times)then24return025end26return1

RedisConfig.java redis配置(该配置继承了CachingConfigurerSupport)中对写入redis的数据的序列化。

如果使用IP锁的时候,错误出现在了AOP中的使用脚本写入redis的时候(像什么Long无法转String的错误),基本是这边序列化没配好。

1@Bean2@SuppressWarnings(value={"unchecked","rawtypes"})3publicRedisTemplate<Object,Object>redisTemplate(RedisConnectionFactoryconnectionFactory)4{5RedisTemplate<Object,Object>template=newRedisTemplate<>();6template.setConnectionFactory(connectionFactory);7FastJson2JsonRedisSerializerserializer=newFastJson2JsonRedisSerializer(Object.class);8//使用StringRedisSerializer来序列化和反序列化redis的key值9template.setKeySerializer(newStringRedisSerializer());10template.setValueSerializer(serializer);11//Hash的key也采用StringRedisSerializer的序列化方式12template.setHashKeySerializer(newStringRedisSerializer());13template.setHashValueSerializer(serializer);14template.afterPropertiesSet();15returntemplate;16}

使用示范。

1@PostMapping("/test")2@IpLimiter(limit=2,time=5,message="您访问过于频繁,请稍候访问",lockUri=true)3publicAjaxResulttest(@RequestBodyMapmap){4//代码......5}
声明:本站所有文章,如无特殊说明或标注,均为爬虫抓取以及网友投稿,版权归原作者所有。