微服务架构和实践架构

限流组件的实现思路-(第一版)

2019-07-01  本文已影响2人  罗曼蒂克

借助 redis,
根据业务设计唯一的 key.
使用配置参数(一定时间内可发送的次数)count作为 value
使用配置参数(时间)作为该 key的过期时间.

逻辑:
每次发送时检查是否存在该 key,和次数是否达到上限,已达上限不发送;
如果不存在或者未达上限,则发送,然后 count++,同时更新过期时间

ps:
关于过期时间有两点歧义:是否需要续期,因此做成了可配置的.



public class LimitService {
    private final String value = "value";
    private final String createTime = "create_time";
    Jedis jedis;

    @Before
    public void before() {
        jedis = new Jedis("localhost");
    }

    @Test
    public void test() {
        execute();
    }

    private static final int count=2;
    private static final int second=10;
    //数值变化更新有效期
    private static final boolean INCREASE_VALUE_REFRESH_TTL = false;

    private static final String key = "limit_component";

    public void execute() {
        if (check()) {
            System.out.println("执行方法");
        }
    }

    private boolean check() {
        boolean result ;
        int currentCount=0;
        if (!jedis.exists(key)) {
            result = true;
            setKey(currentCount);
        } else {
            String s = jedis.hget(key, value);
            currentCount= Convert.toInt(s);
            if (currentCount >= count) {
                //大于等于超限啦
                result = false;
            } else {
                result = true;
                setKey(currentCount);
            }
        }
        System.out.println(StrUtil.format("检查结果【{}】",result));
        return result;
    }

    private void setKey(int currentCount) {
        currentCount++;
        Boolean exists = jedis.exists(key);
        jedis.hset(key, value, Convert.toStr(currentCount));
        if (INCREASE_VALUE_REFRESH_TTL ||!exists) {
            //续期
            jedis.expire(key, second);
            if (!exists) {
                jedis.hset(key, createTime, Convert.toStr(System.currentTimeMillis()));
            }
        }
    }


}

后边会考虑使用注解来定义配置项

上一篇 下一篇

猜你喜欢

热点阅读