redis 执行 lua脚本2

数据存储

2017-06-18

430

0

技术:redis + lua + java8

运行环境:windows redis3 + lua + windows 10

demo功能:演示redis中执行lua脚本,批量获取多个key的值

进阶功能: 初级是 每次都会发送脚本给redis, 本demo是先将脚本保存到redis, 再进行调用,提供效率

地址信息

redis脚本基本调用: http://demoworld.tech/c/redis_run_lua

源代码地址:http://git.oschina.net/youlixishi/demo-world/

初始化脚本

在初始化调用对象 ScriptTest 时 , 先初始化。 这里放在静态构造函数中初始化。 只能初始化一次哦

public static String scripts="脚本太多, 请下载源代码看";
public static String strSHA = "";

static {
   strSHA = CacheHelper.INSTANCE.loadScript(ScriptTest.scripts);
}

调用脚本

//测试入口
@Test
public void test1() {
    CacheHelper.INSTANCE.set("a", "a");
    CacheHelper.INSTANCE.set("b", "b");
    CacheHelper.INSTANCE.set("c", "c");
    String[] params = new String[3];
    Object tmpObj = CacheHelper.INSTANCE.evalSHA(strSHA, "a,b,c");
    List tmpList = (ArrayList) tmpObj;
    tmpList.forEach(x -> {
        System.out.println(x);
    });
}
//加载脚本
public String loadScript(String scripts){
    Jedis jedis = null;
    String tmpSHA= null;
    try {
        jedis = jedisPool.getResource();
        tmpSHA = jedis.scriptLoad(scripts);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return tmpSHA;
}
// 执行脚本
public Object evalSHA(String scriptsSHA, String... params) {
    Jedis jedis = null;
    Object tmpResult = null;
    try {
        jedis = jedisPool.getResource();
        tmpResult = jedis.evalsha(scriptsSHA, params != null ? params.length : 0, params);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return tmpResult;
}
 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think