国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

JAVA:基于Redis 實現(xiàn)計數(shù)器限流

這篇具有很好參考價值的文章主要介紹了JAVA:基于Redis 實現(xiàn)計數(shù)器限流。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1、簡述

在現(xiàn)實世界中可能會出現(xiàn)服務(wù)器被虛假請求轟炸的情況,因此您可能希望控制這種虛假的請求。
一些實際使用情形可能如下所示:

  • API配額管理-作為提供者,您可能希望根據(jù)用戶的付款情況限制向服務(wù)器發(fā)出API請求的速率。這可以在客戶端或服務(wù)端實現(xiàn)。

  • 安全性-防止DDOS攻擊。

  • 成本控制–這對服務(wù)方甚至客戶方來說都不是必需的。如果某個組件以非常高的速率發(fā)出一個事件,它可能有助于控制它,它可能有助于控制從客戶端發(fā)送的請求。

常見的限流算法:令牌桶算法, 漏桶算法。比較成熟的有分布式hystrix, sentinel,還有g(shù)uava高并發(fā)限流ratelimiter。本文主要是介紹Redis如何對指定的key進(jìn)行計數(shù)限流的。

2、引用和配置

引用redis的maven包,包括客戶端連接插件jedis。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
</dependency>

在application.yml配置中添加Redis服務(wù)端配置:

spring:
  #redis配置#
  redis:
    database: 0
    host: 192.168.254.128
    port: 6379
    password: 123456
    timeout: 5000
    jedis:
      pool:
        max-active: 8
        max-wait: 5000
        max-idle: 8
        min-idle: 1

3、Config配置

添加redis configuration配置bean和redis存儲json轉(zhuǎn)換。

@Configuration
public class MyRedisConfig {
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.database}")
    private int database;

    //@SuppressWarnings("all")
    @Bean
    public StringRedisTemplate redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(host);
        configuration.setPassword(RedisPassword.of(password));
        configuration.setPort(port);
        configuration.setDatabase(database);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(configuration);
        jedisConnectionFactory.getPoolConfig().setMaxIdle(30);
        jedisConnectionFactory.getPoolConfig().setMinIdle(10);
        return jedisConnectionFactory;
    }
}

4、添加組件

添加自定義的限速攔截器組件,到時候攔截器會根據(jù)該組件注釋來攔截對應(yīng)的接口請求,實現(xiàn)跟業(yè)務(wù)解耦。


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RequestLimit {

    /**
     * 調(diào)用方唯一key的名字
     *
     * @return
     */
    String name();
    /**
     * 限制訪問次數(shù)
     * @return
     */
    int limitTimes();

    /**
     * 限制時長,也就是計數(shù)器的過期時間
     *
     * @return
     */
    long timeout();

    /**
     * 限制時長單位
     *
     * @return
     */
    TimeUnit timeUnit();
}
  • name :表示請求方唯一的身份參數(shù),如userId,token等。
  • limitTimes :表示限制訪問次數(shù),也就是他在指定時間內(nèi)可以訪問多少次。
  • timeout:表示限制訪問次數(shù)的有效期,一分鐘還是一個小時。
  • timeUnit:表示限速實際的單位,秒、分鐘、小時等

5、攔截器

添加攔截器實現(xiàn)HandlerInterceptor 來實現(xiàn)對添加@RequestLimit 進(jìn)行攔截處理當(dāng)前請求在規(guī)定的時間是否超出。當(dāng)前采用的是redis的BoundValueOperations 來計算請求次數(shù)在規(guī)定的時間內(nèi)是否異常。

/**
 * 請求限流攔截器
 */
@Slf4j
@Component
public class RequestLimitInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //判斷接口是否添加requestLimit
            if(handlerMethod.hasMethodAnnotation(RequestLimit.class)){
                RequestLimit requestLimit = handlerMethod.getMethod().getAnnotation(RequestLimit.class);
                JSONObject object = new JSONObject();
                String token = request.getParameter(requestLimit.name());
                response.setContentType("text/json;charset=utf-8");
                object.put("timestamp", System.currentTimeMillis());
                BoundValueOperations<String, Integer> boundValueOperations = redisTemplate.boundValueOps(token);
                if(StringUtils.isEmpty(token)){
                    object.put("result", "token is invalid");
                    response.getWriter().print(JSON.toJSONString(object));
                } else if(checkLimit(token,requestLimit)){
                    object.put("result","token is success,請求成功");
                     long expire = boundValueOperations.getExpire();
                    return true;
                }else {
                    object.put("result", "達(dá)到訪問次數(shù)上限,禁止訪問!");
                    response.getWriter().print(JSON.toJSONString(object));
                }
                return false;
            }
        }
        return true;
    }

    /**
     * 限速校驗
     * @param token
     * @param limit
     * @return
     */
    private Boolean checkLimit(String token, RequestLimit limit){
        BoundValueOperations<String , Integer> boundValueOperations = redisTemplate.boundValueOps(token);
        Integer count  = boundValueOperations.get();
        if(Objects.isNull(count)){
            redisTemplate.boundValueOps(token).set(1,limit.timeout(), limit.timeUnit());
        }else if(count > limit.limitTimes()){
            return Boolean.FALSE;
        }else {
            redisTemplate.boundValueOps(token).set(++count, boundValueOperations.getExpire(),limit.timeUnit());
        }
        return  Boolean.TRUE;
    }
}

實現(xiàn)攔截器后我們需要將當(dāng)前攔截器添加到WebMvcConfigurer攔截器中:

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Autowired
    private RequestLimitInterceptor requestLimitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestLimitInterceptor).addPathPatterns("/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }

}

這樣我們就完成了簡易的攔截限速器,我們在請求的接口前添加@RequestLimit就可以限速了:

/**
 * 分頁查詢
 * @param param
 * @return
 */
@RequestLimit(name = "token", limitTimes = 20, timeout = 60, timeUnit = TimeUnit.SECONDS)
@GetMapping("/page")
public R page(TagParam param) {
    Query query = param.toQuery();

    PageInfo<Tag> pageInfo = tagService.page(query);
    return R.ok().put("pageInfo", pageInfo);
}

6、BoundValueOperations 使用

6.1 BoundValueOperations

就是一個綁定key的對象,我們可以通過這個對象來進(jìn)行與key相關(guān)的操作

BoundValueOperations boundValueOps = redisTemplate.boundValueOps("token");
6.2 set(V value)

給綁定鍵重新設(shè)置值(如果沒有值,則會添加這個值)

boundValueOps.set("token");
6.3 get()

獲取綁定鍵的值。

String str = (String) boundValueOps.get();
System.out.println(str);
6.4 set(V value, long timeout, TimeUnit unit)

給綁定鍵設(shè)置新值并設(shè)置過期時間

boundValueOps.set("token",30, TimeUnit.SECONDS);
6.5 getAndSet(V value)

如果有這個值則獲取沒有則設(shè)置

String oldValue = (String) boundValueOps.getAndSet("token");
String newValue = (String) boundValueOps.get();
6.6 increment(double delta)和increment(long delta)

它是Redis的自增長鍵,前提是綁定值的類型是double或long類型。increment是單線程的,所以它是安全的。

BoundValueOperations boundValueOps = redisTemplate.boundValueOps("token");
boundValueOps.set(1);
System.out.println(boundValueOps.get());
boundValueOps.increment(1);
System.out.println(boundValueOps.get());

注意!使用該方法,需要使用StringRedisSerializer序列化器才能使用increment方法,否則會報錯

7、代碼地址

不管代碼實現(xiàn)方式如何,還是要自己動手來實現(xiàn)才能體驗設(shè)計的思想,讓自己成長的更快,理解的更透徹。

代碼地址:https://gitee.com/lhdxhl/redis.git
參考文章:https://zhuanlan.zhihu.com/p/427906048
JAVA:基于Redis 實現(xiàn)計數(shù)器限流文章來源地址http://www.zghlxwxcb.cn/news/detail-430857.html

到了這里,關(guān)于JAVA:基于Redis 實現(xiàn)計數(shù)器限流的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包