通过reids实现
限流的流程图
在配置文件配置限流参数
blackip: # ip 连续请求的次数 continue-counts: ${counts:3} # ip 判断的时间间隔,单位:秒 time-interval: ${interval:20} # 限制的时间,单位:秒 limit-time: ${time:30}
编写全局过滤器类
package com.ajie.gateway.filter; import com.ajie.common.enums.responsestatusenum; import com.ajie.common.result.gracejsonresult; import com.ajie.common.utils.collutils; import com.ajie.common.utils.iputil; import com.ajie.common.utils.jsonutils; import com.ajie.common.utils.redisutil; import io.netty.handler.codec.http.httpheadernames; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.annotation.value; import org.springframework.cloud.gateway.filter.gatewayfilterchain; import org.springframework.cloud.gateway.filter.globalfilter; import org.springframework.core.ordered; import org.springframework.core.io.buffer.databuffer; import org.springframework.http.httpstatus; import org.springframework.http.server.reactive.serverhttprequest; import org.springframework.http.server.reactive.serverhttpresponse; import org.springframework.stereotype.component; import org.springframework.util.antpathmatcher; import org.springframework.util.mimetypeutils; import org.springframework.web.server.serverwebexchange; import reactor.core.publisher.mono; import java.nio.charset.standardcharsets; import java.util.list; import java.util.concurrent.timeunit; /** * @description: * @author: ajie */ @slf4j @component public class iplimitfilterjwt implements globalfilter, ordered { @autowired private urlpathproperties urlpathproperties; @value("${blackip.continue-counts}") private integer continuecounts; @value("${blackip.time-interval}") private integer timeinterval; @value("${blackip.limit-time}") private integer limittime; private final antpathmatcher antpathmatcher = new antpathmatcher(); @override public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) { // 1.获取当前的请求路径 string path = exchange.getrequest().geturi().getpath(); // 2.获得所有的需要限流的url list<string> iplimiturls = urlpathproperties.getiplimiturls(); // 3.校验并且排除excludelist if (collutils.isnotempty(iplimiturls)) { for (string url : iplimiturls) { if (antpathmatcher.matchstart(url, path)) { log.warn("iplimitfilterjwt--url={}", path); // 进行ip限流 return dolimit(exchange, chain); } } } // 默认直接放行 return chain.filter(exchange); } private mono<void> dolimit(serverwebexchange exchange, gatewayfilterchain chain) { // 获取真实ip serverhttprequest request = exchange.getrequest(); string ip = iputil.getip(request); /** * 需求: * 判断ip在20秒内请求的次数是否超过3次 * 如果超过,则限制访问30秒 * 等待30秒以后,才能够恢复访问 */ // 正常ip string iprediskey = "gateway_ip:" + ip; // 被拦截的黑名单,如果存在,则表示该ip已经被限制访问 string ipredislimitedkey = "gateway_ip:limit:" + ip; long limitlefttime = redisutil.keyops.getexpire(ipredislimitedkey); if (limitlefttime > 0) { return rendererrormsg(exchange, responsestatusenum.system_error_black_ip); } // 在redis中获得ip的累加次数 long requesttimes = redisutil.stringops.incrby(iprediskey, 1); // 如果访问次数为1,则表明是第一次访问,在redis设置倒计时 if (requesttimes == 1) { redisutil.keyops.expire(iprediskey, timeinterval, timeunit.seconds); } // 如果访问次数超过限制的次数,直接将该ip存入限制的redis key,并设置限制访问时间 if (requesttimes > continuecounts) { // 设置该ip需要被限流的时间 redisutil.stringops.setex(ipredislimitedkey, ip, limittime, timeunit.seconds); return rendererrormsg(exchange, responsestatusenum.system_error_black_ip); } return chain.filter(exchange); } public mono<void> rendererrormsg(serverwebexchange exchange, responsestatusenum statusenum) { // 1.获得response serverhttpresponse response = exchange.getresponse(); // 2.构建jsonresult gracejsonresult jsonresult = gracejsonresult.exception(statusenum); // 3.修改response的code为500 response.setstatuscode(httpstatus.internal_server_error); // 4.设定header类型 if (!response.getheaders().containskey("content-type")) { response.getheaders().add(httpheadernames.content_type.tostring(), mimetypeutils.application_json_value); } // 5.转换json并且向response写入数据 string jsonstr = jsonutils.tojsonstr(jsonresult); databuffer databuffer = response.bufferfactory() .wrap(jsonstr.getbytes(standardcharsets.utf_8)); return response.writewith(mono.just(databuffer)); } @override public int getorder() { return 1; } }
通过lua+redis实现
业务流程还是和上图差不多,只不过gateway网关不用再频繁和redis进行交互。整个限流逻辑放在redis层,通过lua代码嵌套
lua实现限流的代码
--[[ ipredislimitedkey:限流的redis key iprediskey:未被限流的redis key,通过此key计算访问次数 timeinterval:访问时间间隔,在此时间内,访问到指定次数进行限流 limittime:限流的时长 ]] -- 判断当前ip是否已经被限流 if redis.call("ttl", ipredislimitedkey) > 0 then return 1 end -- 如果没有被限流,就让当前ip在redis中的值累计1 local requesttimes = redis.call("incrby", iprediskey, 1) -- 判断累加后的值 if requesttimes == 1 then -- 如果累加后的值是1,说明是第一次请求,设置一个时间间隔 redis.call("expire", iprediskey, timeinterval) return 0 elseif requesttimes > continuecounts then -- 如果累加后的值超过了设定的阈值,就对当前ip进行限流 redis.call("setex", ipredislimitedkey, limittime, ip) return 1 end
java代码实现lua和redis的整合
package com.ajie.gateway.filter; import com.ajie.common.enums.responsestatusenum; import com.ajie.common.result.gracejsonresult; import com.ajie.common.utils.collutils; import com.ajie.common.utils.iputil; import com.ajie.common.utils.jsonutils; import com.ajie.common.utils.redisutil; import com.google.common.collect.lists; import io.netty.handler.codec.http.httpheadernames; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.annotation.value; import org.springframework.cloud.gateway.filter.gatewayfilterchain; import org.springframework.cloud.gateway.filter.globalfilter; import org.springframework.core.ordered; import org.springframework.core.io.buffer.databuffer; import org.springframework.http.httpstatus; import org.springframework.http.server.reactive.serverhttprequest; import org.springframework.http.server.reactive.serverhttpresponse; import org.springframework.stereotype.component; import org.springframework.util.antpathmatcher; import org.springframework.util.mimetypeutils; import org.springframework.web.server.serverwebexchange; import reactor.core.publisher.mono; import java.nio.charset.standardcharsets; import java.util.list; /** * @description: * @author: ajie */ @slf4j @component public class iplualimitfilterjwt implements globalfilter, ordered { @autowired private urlpathproperties urlpathproperties; @value("${blackip.continue-counts}") private integer continuecounts; @value("${blackip.time-interval}") private integer timeinterval; @value("${blackip.limit-time}") private integer limittime; private final antpathmatcher antpathmatcher = new antpathmatcher(); @override public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) { // 1.获取当前的请求路径 string path = exchange.getrequest().geturi().getpath(); // 2.获得所有的需要限流的url list<string> iplimiturls = urlpathproperties.getiplimiturls(); // 3.校验并且排除excludelist if (collutils.isnotempty(iplimiturls)) { for (string url : iplimiturls) { if (antpathmatcher.matchstart(url, path)) { log.warn("iplimitfilterjwt--url={}", path); // 进行ip限流 return dolimit(exchange, chain); } } } // 默认直接放行 return chain.filter(exchange); } private mono<void> dolimit(serverwebexchange exchange, gatewayfilterchain chain) { // 获取真实ip serverhttprequest request = exchange.getrequest(); string ip = iputil.getip(request); /** * 需求: * 判断ip在20秒内请求的次数是否超过3次 * 如果超过,则限制访问30秒 * 等待30秒以后,才能够恢复访问 */ // 正常ip string iprediskey = "gateway_ip:" + ip; // 被拦截的黑名单,如果存在,则表示该ip已经被限制访问 string ipredislimitedkey = "gateway_ip:limit:" + ip; // 通过redis执行lua脚本。返回1代表限流了,返回0代表没有限流 string script = "if tonumber(redis.call('ttl', keys[2])) > 0 then return 1 end local" + " requesttimes = redis.call('incrby', keys[1], 1) if tonumber(requesttimes) == 1 then" + " redis.call('expire', keys[1], argv[2]) return 0 elseif tonumber(requesttimes)" + " > tonumber(argv[1]) then redis.call('setex', keys[2], argv[3], argv[4])" + " return 1 else return 0 end"; long result = redisutil.helper.execute(script, long.class, lists.newarraylist(iprediskey, ipredislimitedkey), continuecounts, timeinterval, limittime, ip); if(result == 1){ return rendererrormsg(exchange, responsestatusenum.system_error_black_ip); } return chain.filter(exchange); } public mono<void> rendererrormsg(serverwebexchange exchange, responsestatusenum statusenum) { // 1.获得response serverhttpresponse response = exchange.getresponse(); // 2.构建jsonresult gracejsonresult jsonresult = gracejsonresult.exception(statusenum); // 3.修改response的code为500 response.setstatuscode(httpstatus.internal_server_error); // 4.设定header类型 if (!response.getheaders().containskey("content-type")) { response.getheaders().add(httpheadernames.content_type.tostring(), mimetypeutils.application_json_value); } // 5.转换json并且向response写入数据 string jsonstr = jsonutils.tojsonstr(jsonresult); databuffer databuffer = response.bufferfactory() .wrap(jsonstr.getbytes(standardcharsets.utf_8)); return response.writewith(mono.just(databuffer)); } @override public int getorder() { return 1; } }
注意事项
在编写lua脚本的时候最好不要一次性写完去试,因为无法进行调试,最好进行拆解。
在进行数字比较时建议加上
tonumber()
。如果是通过方法传参进来的一定要加,因为redistemplate默认会把参数当做字符串传入如果不转数字就会出现上面的错误
最后也是最重要的,lua代码逻辑一定要对,否则得不到自己想要的结果需要排查很久
总结
到此这篇关于redis实现ip限流的2种方式的文章就介绍到这了,更多相关redis实现ip限流内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论