利用redis做限流器

    xiaoxiao2022-07-13  136

    package com.inspur.inspurTest.test.redis; import redis.clients.jedis.Jedis; /** * author yulinshan * time 2019/5/23 * 限流器,利用redis的incr函数做计数,expire做计时失效 **/ public class Increase { static String key = "count"; static int limitCount = 30; public static void main(String[] args) throws InterruptedException { Jedis j =new Jedis("127.0.0.1",6379); for(int i = 0 ;i < 100 ;i ++ ) { if (!checkKey(j)){ System.out.println("超过限流阈值"); return; } incrKey(j); } } private static void incrKey(Jedis j){ if (j.ttl(key) < 0 ){ j.incr(key); j.expire(key,60); }else{ j.incr(key); } System.out.println("总计访问次数为:"+j.get(key)); } private static boolean checkKey(Jedis j) { if (null != j.get(key)) { if (Integer.parseInt(j.get(key)) >= limitCount) { return false; } } return true; } }

    以上的代码借鉴了《架构修炼之道》第90页代码。以上逻辑可以放在网关项目中,对某些请求做限流。用到了包

    compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
    最新回复(0)