redis+lua分布式高并发--限流算法

lua脚本 limit.lua

local key = KEYS[1]
local limit = tonumber(ARGV[1])
local current = tonumber(redis.call('get', key) or '0')
if current + 1 > limit then
  return 0
else ---- 设置有效期为1秒钟
  redis.call("INCRBY", key,"1")
  redis.call("expire", key,"1")
  return 1
end

java代码

    // redis server
    protected static final String HOST_NAME = "192.168.1.29";
    //redis 端口
    protected static final int PORT = 6379;

    public RedisTemplate<String, String> getFactory() {

        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setDatabase(0);
        config.setHostName(HOST_NAME);
        config.setPort(PORT);

        RedisTemplate<String, String> redisTemplate = new StringRedisTemplate();
        JedisConnectionFactory factory = new JedisConnectionFactory(config);
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setScriptExecutor(new DefaultScriptExecutor(redisTemplate));
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
		
    public static void main(String[] args) {
        RedisUtils utils = new RedisUtils();
        RedisTemplate<String, String> redisTemplate = utils.getFactory();
        /*限流脚本位置*/
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setLocation(new ClassPathResource("limit.lua"));
        redisScript.setResultType(java.lang.Long.class);
        String current = String.valueOf(System.currentTimeMillis());
        // redisTemplate.execute(redisScript);
        while(true) {
            Long id = redisTemplate.execute(redisScript, Collections.singletonList(
                    "ratelimit:app"
            ), "50");
            if(id == 0){
                /*超出限流数量,直接返回*/
                break;
            }
            /*为限流*/
            System.out.println(id);
        }
    }

你可能感兴趣的:(redis+lua分布式高并发--限流算法)