zoukankan      html  css  js  c++  java
  • 基于redis+lua实现的分布式限流

    public class Console {

    public static void main(String[] args) {
        Config config = new Config();
        config.setLockWatchdogTimeout(10000);
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        RedissonClient redissonClient = Redisson.create(config);
    
        List<Object> keys = new ArrayList<>();
        keys.add("txk");
        Object[] values=new Object[]{1};
        Object eval = redissonClient.getScript().eval(READ_WRITE, RedisLua.LIMIT_LUA_STRING, RScript.ReturnType.INTEGER, keys, values);
        System.out.println(eval);
    
    }
    
    
    static class RedisLua {
    
        public static final String LIMIT_LUA_STRING;
    
        static {
            StringBuilder limitLuaString =new StringBuilder();
            limitLuaString.append(" local key = KEYS[1]");
            limitLuaString.append("
    local limit = tonumber(ARGV[1])");
            limitLuaString.append("
    local curentLimit = tonumber(redis.call('get', key) or "0")");
            limitLuaString.append("
    if curentLimit + 1 > limit then");
            limitLuaString.append("
    return 0");
            limitLuaString.append("
    else");
            limitLuaString.append("
     redis.call("INCRBY", key, 1)");
            limitLuaString.append("
    redis.call("EXPIRE", key, ARGV[2])");
            limitLuaString.append("
    return curentLimit + 1");
            limitLuaString.append("
    end");
            LIMIT_LUA_STRING=limitLuaString.toString();
        }
    }
    

    }

  • 相关阅读:
    BOOST 线程完全攻略
    BOOST 线程完全攻略
    BOOST 线程完全攻略
    BOOST 线程完全攻略
    Boost线程库学习笔记
    BOOST中如何实现线程安全代码
    多线程 AfxBeginThread 与 CreateThread 的区别
    AfxBeginThread的介绍/基本用法
    淘宝开源项目
    数据库中间件OneProxy and onemysql
  • 原文地址:https://www.cnblogs.com/merciless/p/14201332.html
Copyright © 2011-2022 走看看