【redis】redis分布式限流

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.IntegerCodec;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ChunLian.Yang
 * @since 2018-02-02
 */
@Slf4j
public class TestRedissonRate {

  private final RedissonClient redisClient;
  private final String key = "msgRateLimiter:" + "test";
  private final int limiter = 10000;

  @Autowired
  public TestRedissonRate(RedissonClient redisClient) {
    this.redisClient = redisClient;
  }

  //服务启动的时候,先清一下 redis,防止 count 出错
  public void reload() {
    RMapCache msgRateLimit =
        redisClient.getMapCache(key, IntegerCodec.INSTANCE);
    if (msgRateLimit.containsKey(key)) {
      msgRateLimit.delete();
    }
  }

  //该方法可以配合 mq,结果是 true 的话就 ack,false 的话就 reject
  public boolean handleMessage() {
    //分布式场景下的限流
    //String key = "msgRateLimiter:" + MsgConstants.MsgType.APP_PUSH[0];
    RMapCache msgRateLimit =
        redisClient.getMapCache(key, IntegerCodec.INSTANCE);
    Integer count;
    try {
      msgRateLimit.putIfAbsent(key, 0, 1L, TimeUnit.SECONDS);
      count = msgRateLimit.addAndGet(key, 1);
      log.info("get redis counter:{}", count);
      if (count < limiter) {
        //此处是你要执行的代码
        return true;
      }
      log.warn("超过限流:{}", count);
    } catch (Exception e) {
      log.error("err", e);
    }
    return false;
  }
}
 
      org.redisson
      redisson
      3.4.1
    

引用:https://my.oschina.net/yangchunlian/blog/1617766

你可能感兴趣的:(【redis】redis分布式限流)