Redis 接口限流

dependency

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.0</version>
        </dependency>

class Constant

public class Constant {
    public static final int REDIS_PORT = 6379;
    public static final String REDIS_IP = "localhost";// 需要自行修改
    public static final String REDIS_TEST_ZSET_KEY = "testZsetKey";
}

class CurrentLimiter

import com.tbryant.test.domain.Constant;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.io.IOException;

/**
 * @auther TBryant
 * @date 2021/5/27 13:44
 */
public class CurrentLimiter {
    private static final Jedis JEDIS = new Jedis(Constant.REDIS_IP, Constant.REDIS_PORT);

    /**
     * @param value 不允许重复,否则会产生误差
     */
    static boolean doCurrentLimiterValid(String apiName, String value, int maxCount) {
        long currentTimeMillis = System.currentTimeMillis();
        long score = currentTimeMillis / 1000;
        Pipeline pipe = JEDIS.pipelined();
        pipe.multi();
        // 删除一秒之前的数据
        pipe.zremrangeByScore(apiName, 0, score - 1);
        pipe.zadd(apiName, score, value);
        Response<Long> count = pipe.zcard(apiName);
        // 设置过期时间
        pipe.expire(apiName, 3);
        pipe.exec();
        try {
            pipe.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count.get() <= maxCount;
    }
}

class CurrentLimiterTest

import com.tbryant.test.domain.Constant;

/**
 * @auther TBryant
 * @date 2021/5/27 13:44
 */
public class CurrentLimiterTest {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (CurrentLimiter.doCurrentLimiterValid(Constant.REDIS_TEST_ZSET_KEY, i + "", 10)){
                System.out.println("=====请求成功=====");
            }else{
                System.out.println("限流处理");
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值