最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot如何使用自定義注解實現(xiàn)接口限流

 更新時間:2022年06月07日 10:51:28   作者:Asurplus  
這篇文章主要介紹了SpringBoot如何使用自定義注解實現(xiàn)接口限流,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用自定義注解實現(xiàn)接口限流

在高并發(fā)系統(tǒng)中,保護(hù)系統(tǒng)的三種方式分別為:緩存,降級和限流。

限流的目的是通過對并發(fā)訪問請求進(jìn)行限速或者一個時間窗口內(nèi)的的請求數(shù)量進(jìn)行限速來保護(hù)系統(tǒng),一旦達(dá)到限制速率則可以拒絕服務(wù)、排隊或等待。

1、自定義限流注解

import com.asurplus.common.enums.LimitType;
import java.lang.annotation.*;
/**
 * 限流注解
 *
 * @author Lizhou
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Limit {
    /**
     * 限流key前綴
     */
    String prefix() default "limit:";
    /**
     * 限流時間,單位秒
     */
    int time() default 60;
    /**
     * 限流次數(shù)
     */
    int count() default 10;
    /**
     * 限流類型
     */
    LimitType type() default LimitType.DEFAULT;
}

2、限流類型枚舉類

/**
?* 限流類型
?*
?* @author Lizhou
?*/
public enum LimitType {
? ? /**
? ? ?* 默認(rèn)策略全局限流
? ? ?*/
? ? DEFAULT,
? ? /**
? ? ?* 根據(jù)請求者IP進(jìn)行限流
? ? ?*/
? ? IP
}

我們定義了兩種限流類型,分別為全局限流和 IP 限流,全局限流對訪問接口的所有用戶進(jìn)行限流保護(hù),IP 限流對每個 IP 請求用戶進(jìn)行單獨(dú)限流保護(hù)。

3、限流 Lua 腳本

1、由于我們使用 Redis 進(jìn)行限流,我們需要引入 Redis 的 maven 依賴,同時需要引入 aop 的依賴

<!-- aop依賴 -->
<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- redis依賴 -->
<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

在配置文件中配置 Redis 的連接信息,具體參考:SpringBoot中整合Redis

2、限流腳本

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
?* 接口限流
?*/
@Slf4j
@Component
public class RedisLimitUtil {
? ? @Autowired
? ? private StringRedisTemplate redisTemplate;
? ? /**
? ? ?* 限流
? ? ?*
? ? ?* @param key ? 鍵
? ? ?* @param count 限流次數(shù)
? ? ?* @param times 限流時間
? ? ?* @return
? ? ?*/
? ? public boolean limit(String key, int count, int times) {
? ? ? ? try {
? ? ? ? ? ? String script = "local lockKey = KEYS[1]\n" +
? ? ? ? ? ? ? ? ? ? "local lockCount = KEYS[2]\n" +
? ? ? ? ? ? ? ? ? ? "local lockExpire = KEYS[3]\n" +
? ? ? ? ? ? ? ? ? ? "local currentCount = tonumber(redis.call('get', lockKey) or \"0\")\n" +
? ? ? ? ? ? ? ? ? ? "if currentCount < tonumber(lockCount)\n" +
? ? ? ? ? ? ? ? ? ? "then\n" +
? ? ? ? ? ? ? ? ? ? " ? ?redis.call(\"INCRBY\", lockKey, \"1\")\n" +
? ? ? ? ? ? ? ? ? ? " ? ?redis.call(\"expire\", lockKey, lockExpire)\n" +
? ? ? ? ? ? ? ? ? ? " ? ?return true\n" +
? ? ? ? ? ? ? ? ? ? "else\n" +
? ? ? ? ? ? ? ? ? ? " ? ?return false\n" +
? ? ? ? ? ? ? ? ? ? "end";
? ? ? ? ? ? RedisScript<Boolean> redisScript = new DefaultRedisScript<>(script, Boolean.class);
? ? ? ? ? ? List<String> keys = Arrays.asList(key, String.valueOf(count), String.valueOf(times));
? ? ? ? ? ? return redisTemplate.execute(redisScript, keys);
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? log.error("限流腳本執(zhí)行失?。簕}", e.getMessage());
? ? ? ? }
? ? ? ? return false;
? ? }
}

通過 Lua 腳本,根據(jù) Redis 中緩存的鍵值判斷限流時間(也是 key 的過期時間)內(nèi),訪問次數(shù)是否超出了限流次數(shù),沒超出則訪問次數(shù) +1,返回 true,超出了則返回 false。

4、限流切面處理類 

import com.asurplus.common.annotation.Limit;
import com.asurplus.common.enums.LimitType;
import com.asurplus.common.exception.CustomException;
import com.asurplus.common.ip.IpUtil;
import com.asurplus.common.redis.RedisLimitUtil;
import com.asurplus.common.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
?* 限流處理
?*
?* @author Lizhou
?*/
@Slf4j
@Aspect
@Component
public class LimitAspect {
? ? @Autowired
? ? private RedisLimitUtil redisLimitUtil;
? ? /**
? ? ?* 前置通知,判斷是否超出限流次數(shù)
? ? ?*
? ? ?* @param point
? ? ?*/
? ? @Before("@annotation(limit)")
? ? public void doBefore(JoinPoint point, Limit limit) {
? ? ? ? try {
? ? ? ? ? ? // 拼接key
? ? ? ? ? ? String key = getCombineKey(limit, point);
? ? ? ? ? ? // 判斷是否超出限流次數(shù)
? ? ? ? ? ? if (!redisLimitUtil.limit(key, limit.count(), limit.time())) {
? ? ? ? ? ? ? ? throw new CustomException("訪問過于頻繁,請稍候再試");
? ? ? ? ? ? }
? ? ? ? } catch (CustomException e) {
? ? ? ? ? ? throw e;
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? throw new RuntimeException("接口限流異常,請稍候再試");
? ? ? ? }
? ? }
? ? /**
? ? ?* 根據(jù)限流類型拼接key
? ? ?*/
? ? public String getCombineKey(Limit limit, JoinPoint point) {
? ? ? ? StringBuilder sb = new StringBuilder(limit.prefix());
? ? ? ? // 按照IP限流
? ? ? ? if (limit.type() == LimitType.IP) {
? ? ? ? ? ? sb.append(IpUtil.getIpAddr(HttpRequestUtil.getRequest())).append("-");
? ? ? ? }
? ? ? ? // 拼接類名和方法名
? ? ? ? MethodSignature signature = (MethodSignature) point.getSignature();
? ? ? ? Method method = signature.getMethod();
? ? ? ? Class<?> targetClass = method.getDeclaringClass();
? ? ? ? sb.append(targetClass.getName()).append("-").append(method.getName());
? ? ? ? return sb.toString();
? ? }
}

1、使用我們剛剛的 Lua 腳本判斷是否超出了限流次數(shù),超出了限流次數(shù)后返回一個自定義異常,然后在全局異常中去捕捉異常,返回 JSON 數(shù)據(jù)。

2、根據(jù)注解參數(shù),判斷限流類型,拼接緩存 key 值

5、使用與測試

1、測試方法

@Limit(type = LimitType.DEFAULT, time = 10, count = 2)
@GetMapping("test")
public String test() {
? ? return "請求成功:" + System.currentTimeMillis();
}

使用自定義注解 @Limit,限制為 10 秒內(nèi),允許訪問 2 次

2、測試結(jié)果

第一次 

第二次

第三次

可以看出,前面兩次都成功返回了請求結(jié)果,第三次超出了接口限流次數(shù),返回了自定義異常信息。

SpringBoot工程中限流方式

限流,是防止用戶惡意刷新接口。常見的限流方式有阿里開源的sentinel、redis等。

1、google的guava,令牌桶算法實現(xiàn)限流

Guava的 RateLimiter提供了令牌桶算法實現(xiàn):平滑突發(fā)限流(SmoothBursty)和平滑預(yù)熱限流(SmoothWarmingUp)實現(xiàn)。

// RateLimiter提供了兩個工廠方法,最終會調(diào)用下面兩個函數(shù),生成RateLimiter的兩個子類。
static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) {
??? ?RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */);
? ? rateLimiter.setRate(permitsPerSecond);
??? ?return rateLimiter;
}
static RateLimiter create(
??? ?SleepingStopwatch stopwatch, double permitsPerSecond, long warmupPeriod, TimeUnit unit,
?double coldFactor) {
??? ?RateLimiter rateLimiter = new SmoothWarmingUp(stopwatch, warmupPeriod, unit, coldFactor);
? ? rateLimiter.setRate(permitsPerSecond);
??? ?return rateLimiter;
}
  • 平滑突發(fā)限流:使用 RateLimiter的靜態(tài)方法創(chuàng)建一個限流器,設(shè)置每秒放置的令牌數(shù)為10個。返回的RateLimiter對象可以保證1秒內(nèi)不會給超過10個令牌,并且以固定速率進(jìn)行放置,達(dá)到平滑輸出的效果。
  • 平滑預(yù)熱限流:RateLimiter的 SmoothWarmingUp是帶有預(yù)熱期的平滑限流,它啟動后會有一段預(yù)熱期,逐步將分發(fā)頻率提升到配置的速率。
@RestController
public class HomeController {
? ? // 這里的10表示每秒允許處理的量為10個
? ? private RateLimiter limiter = RateLimiter.create(10);
? ? private RateLimiter limiter2 = RateLimiter.create(2, 1000, TimeUnit.SECONDS);
? ? //permitsPerSecond: 表示 每秒新增 的令牌數(shù);warmupPeriod: 表示在從 冷啟動速率 過渡到 平均速率 的時間間隔
? ? @GetMapping("/test/{name}")
? ? public String test(@PathVariable("name") String name) {
? ? ? ? // 請求RateLimiter, 超過permits會被阻塞
? ? ? ? final double acquire = limiter.acquire();
? ? ? ? System.out.println("acquire=" + acquire);
? ? ? ? //判斷double是否為空或者為0
? ? ? ? if (acquire == 0) {
? ? ? ? ? ? return name;
? ? ? ? } else {
? ? ? ? ? ? return "操作太頻繁";
? ? ? ? }
? ? }
? ? @AccessLimit(limit = 2, sec = 10)
? ? @GetMapping("/test2/{name}")
? ? public String test2(@PathVariable("name") String name) {
? ? ? ? return name;
? ? }
}

2、interceptor+redis根據(jù)注解限流

public class AccessLimitInterceptor implements HandlerInterceptor {
? ? @Resource
? ? private RedisTemplate<String, Integer> redisTemplate;
? ? @Override
? ? public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
? ? ? ? if (handler instanceof HandlerMethod) {
? ? ? ? ? ? HandlerMethod handlerMethod = (HandlerMethod) handler;
? ? ? ? ? ? Method method = handlerMethod.getMethod();
? ? ? ? ? ? if (!method.isAnnotationPresent(AccessLimit.class)) {
? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? }
? ? ? ? ? ? AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);
? ? ? ? ? ? if (accessLimit == null) {
? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? }
? ? ? ? ? ? int limit = accessLimit.limit();
? ? ? ? ? ? int sec = accessLimit.sec();
? ? ? ? ? ? String key = IPUtil.getIpAddress(request) + request.getRequestURI();
? ? ? ? ? ? //資源唯一標(biāo)識
? ? ? ? ? ? Integer maxLimit = redisTemplate.opsForValue().get(key);
? ? ? ? ? ? if (maxLimit == null) {
? ? ? ? ? ? ? ? //set時一定要加過期時間
? ? ? ? ? ? ? ? redisTemplate.opsForValue().set(key, 1, sec, TimeUnit.SECONDS);
? ? ? ? ? ? } else if (maxLimit < limit) {
? ? ? ? ? ? ? ? redisTemplate.opsForValue().set(key, maxLimit + 1, sec, TimeUnit.SECONDS);
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? output(response, "請求太頻繁!");
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return true;
? ? }
? ? public void output(HttpServletResponse response, String msg) throws IOException {
? ? ? ? response.setContentType("application/json;charset=UTF-8");
? ? ? ? ServletOutputStream outputStream = null;
? ? ? ? try {
? ? ? ? ? ? outputStream = response.getOutputStream();
? ? ? ? ? ? outputStream.write(msg.getBytes("UTF-8"));
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? } finally {
? ? ? ? ? ? outputStream.flush();
? ? ? ? ? ? outputStream.close();
? ? ? ? }
? ? }
? ? @Override
? ? public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
? ? }
? ? @Override
? ? public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
? ? }
}
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
? ? @Bean
? ? public AccessLimitInterceptor accessLimitInterceptor() {
? ? ? ? return new AccessLimitInterceptor();
? ? }
? ? @Override
? ? public void addInterceptors(InterceptorRegistry registry) {
? ? ? ? //addPathPatterns 添加攔截規(guī)則
? ? ? ? registry.addInterceptor(accessLimitInterceptor()).addPathPatterns("/**");
? ? }
? ? @Override
? ? public void addViewControllers(ViewControllerRegistry registry) {
? ? ? ? registry.addViewController("/");
? ? }
}
@Configuration
public class RedisConfig {
? ? @Bean
? ? public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
? ? ? ? RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
? ? ? ? template.setConnectionFactory(redisConnectionFactory);
? ? ? ? template.setKeySerializer(new StringRedisSerializer());
? ? ? ? template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
? ? ? ? template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
? ? ? ? template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
? ? ? ? template.afterPropertiesSet();
? ? ? ? return template;
? ? }
}

限流方式還有很多,后續(xù)繼續(xù)嘗試。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java將一個目錄下的所有數(shù)據(jù)復(fù)制到另一個目錄下

    java將一個目錄下的所有數(shù)據(jù)復(fù)制到另一個目錄下

    這篇文章主要為大家詳細(xì)介紹了java將一個目錄下的所有數(shù)據(jù)復(fù)制到另一個目錄下,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • Java Socket聊天室編程(一)之利用socket實現(xiàn)聊天之消息推送

    Java Socket聊天室編程(一)之利用socket實現(xiàn)聊天之消息推送

    這篇文章主要介紹了Java Socket聊天室編程(一)之利用socket實現(xiàn)聊天之消息推送的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-09-09
  • Java變量和對象的作用域

    Java變量和對象的作用域

    本文主要介紹了Java變量和對象的作用域的相關(guān)知識。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-03-03
  • Java實用工具之StringJoiner詳解

    Java實用工具之StringJoiner詳解

    這篇文章主要介紹了Java實用工具之StringJoiner詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • 詳解Java中類的加載與其初始化

    詳解Java中類的加載與其初始化

    這篇文章主要為大家詳細(xì)介紹了Java中類的加載與其初始化的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,感興趣的小伙伴可以了解一下
    2022-12-12
  • Java設(shè)計模式之單一職責(zé)原則精解

    Java設(shè)計模式之單一職責(zé)原則精解

    設(shè)計模式(Design pattern)代表了最佳的實踐,通常被有經(jīng)驗的面向?qū)ο蟮能浖_發(fā)人員所采用。設(shè)計模式是軟件開發(fā)人員在軟件開發(fā)過程中面臨的一般問題的解決方案。本篇介紹設(shè)計模式七大原則之一的單一職責(zé)原則
    2022-02-02
  • 計算Java數(shù)組長度函數(shù)的方法以及代碼分析

    計算Java數(shù)組長度函數(shù)的方法以及代碼分析

    在本篇內(nèi)容里,小編給大家整理了關(guān)于計算Java數(shù)組長度函數(shù)的方法以及代碼分析內(nèi)容,有興趣的朋友么可以學(xué)習(xí)參考下。
    2022-11-11
  • Mybatis-Plus 搭建與使用入門(小結(jié))

    Mybatis-Plus 搭建與使用入門(小結(jié))

    Mybatis-Plus(簡稱MP)是一個 Mybatis 的增強(qiáng)工具,這篇文章主要介紹了Mybatis-Plus 搭建與使用入門(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • Java實現(xiàn)非阻塞式服務(wù)器的示例代碼

    Java實現(xiàn)非阻塞式服務(wù)器的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何利用Java實現(xiàn)一個簡單的非阻塞式服務(wù)器,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,需要的可以參考一下
    2023-05-05
  • 基于Hibernate中配置文件的學(xué)習(xí)(分享)

    基于Hibernate中配置文件的學(xué)習(xí)(分享)

    下面小編就為大家?guī)硪黄贖ibernate中配置文件的學(xué)習(xí)(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06

最新評論

昌都县| 北川| 闸北区| 晴隆县| 子洲县| 昌江| 喀喇| 安图县| 关岭| 阜城县| 霸州市| 出国| 阿克陶县| 板桥市| 石屏县| 沈丘县| 大方县| 高要市| 南华县| 松滋市| 凤凰县| 曲阜市| 武冈市| 宁安市| 花莲市| 平凉市| 镇巴县| 泗洪县| 岚皋县| 宜丰县| 宜君县| 仙游县| 日土县| 靖宇县| 新河县| 吴旗县| 闽侯县| 天峨县| 延庆县| 浙江省| 巩义市|