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

借助 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()));
            }
        }
    }


}

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 13,871评论 6 13
  • 1.数据结构 1.1字符串 字符串类型的值实际可以是字符串、数字(整数,浮点数),甚至是二进制(图片、视频)...
    Sponge1128阅读 5,133评论 0 0
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,805评论 1 32
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 14,745评论 0 15
  • 今天看到一位朋友写的mysql笔记总结,觉得写的很详细很用心,这里转载一下,供大家参考下,也希望大家能关注他原文地...
    信仰与初衷阅读 10,168评论 0 30