日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

代码示例:使用redis计数来控制单位时间内对某接口的访问量

發(fā)布時間:2025/1/21 编程问答 100 豆豆
生活随笔 收集整理的這篇文章主要介紹了 代码示例:使用redis计数来控制单位时间内对某接口的访问量 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

控制單位時間內(nèi)接口的訪問量

使用redis計數(shù)來控制單位時間內(nèi)對某接口的訪問量,防止刷驗證碼接口之類的。

使用自定義注解的方式,在需要被限制訪問頻率的方法上加注解即可控制。

看實現(xiàn)方式,基于springboot,aop,redis。

新建Springboot工程,引入redis,aop。

創(chuàng)建注解

package com.xueliang.annotation;import org.springframework.core.Ordered; import org.springframework.core.annotation.Order;import java.lang.annotation.*;/*** Created by xueliang on 17/7/6.*/ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented //最高優(yōu)先級 @Order(Ordered.HIGHEST_PRECEDENCE) public @interface RequestLimit {/*** 允許訪問的次數(shù)*/int count() default 5;/*** 時間段,多少時間段內(nèi)運行訪問count次*/long time() default 60000;}

Aspect切面處理邏輯

package com.xueliang.aspect;import com.xueliang.annotation.RequestLimit; import com.xueliang.util.HttpRequestUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest; import java.util.concurrent.TimeUnit;/*** Created by xueliang on 17/7/6.*/ @Component @Aspect public class RequestLimitAspect {private final Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate RedisTemplate<String, String> redisTemplate;@Before("execution(public * com.xueliang.controller.*.*(..)) && @annotation(limit)")public void requestLimit(JoinPoint joinpoint, RequestLimit limit) {// 接收到請求,記錄請求內(nèi)容ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String ip = HttpRequestUtil.getIpAddr(request);String url = request.getRequestURL().toString();String key = "req_limit_".concat(url).concat(ip);//加1后看看值long count = redisTemplate.opsForValue().increment(key, 1);//剛創(chuàng)建if (count == 1) {//設(shè)置1分鐘過期redisTemplate.expire(key, limit.time(), TimeUnit.MILLISECONDS);}if (count > limit.count()) {logger.info("用戶IP[" + ip + "]訪問地址[" + url + "]超過了限定的次數(shù)[" + limit.count() + "]");throw new RuntimeException("超出訪問次數(shù)限制");}} }

獲取IP的工具類

package com.xueliang.util;import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException;/*** Created by xueliang on 17/7/6.*/ public class HttpRequestUtil {/*** 獲取當(dāng)前網(wǎng)絡(luò)ip** @param request* @return*/public static String getIpAddr(HttpServletRequest request) {String ipAddress = request.getHeader("x-forwarded-for");if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("WL-Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getRemoteAddr();if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {//根據(jù)網(wǎng)卡取本機配置的IPInetAddress inet = null;try {inet = InetAddress.getLocalHost();} catch (UnknownHostException e) {e.printStackTrace();}ipAddress = inet.getHostAddress();}}//對于通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15if (ipAddress.indexOf(",") > 0) {ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));}}return ipAddress;} }

通過Controller驗證

@RestController public class IndexController {@RequestLimit(count = 4)@GetMapping("/index")public Object index() {return 1;} }

啟動工程,使用jmeter多次訪問index看看效果即可。

總結(jié)

以上是生活随笔為你收集整理的代码示例:使用redis计数来控制单位时间内对某接口的访问量的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。