Java调用Redis的Lua脚本功能

因网上相关资料不全,在这记录

首先需要redis的java客户端,这里用jedis


      redis.clients
      jedis
      3.1.0

然后这是整合的工具类

public class LuaToRedisDB {

    /**
     * 把文件转化为二进制数组
     * @param filename 脚本的位置
     * @param jedis 客户端对象
     * @return 脚本id
     */
    public byte[] OpenLuaFile(String filename,Jedis jedis) {
        File file = new File(this.getClass().getClassLoader().getResource(filename).getPath());
        byte[] bytes = getFileToByte(file);
        // 发送文件二进制给Redis,返回sha1标识
        byte[] sha1 = jedis.scriptLoad(bytes);
        return  sha1;
    }

    /**
     * 把文件转化为二进制数组
     * @param key 脚本id
     * @param jedis 客户端对象
     * @return 结果
     */
    public String PerformLua(byte[] key,Jedis jedis){
        Object o = jedis.evalsha(key,0);
        return new String((byte[]) o);
    }

    /**
     * 把文件转化为二进制数组
     * @param file 文件
     * @return 二进制数组
     */
    public byte[] getFileToByte(File file) {
        byte[] by = new byte[(int)file.length()];
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            // 从此输入流中读入bb.length个字节放进bb数组
            int ch = is.read(bb);
            while(ch != -1) {
                // 将bb数组中的内容写入到输出流
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            // 将输出流中的内容复制到by数组
            by = bytestream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return by;
    }
}

这是文件结构

-main
    -java
        -MyRedis
            App.java
            LuoToRedisDB.java
        -resources
            -lua
                ceshi.lua

 

这是lua脚本

-- lua
local key = redis.call('get','foo')
key = key ..'\n'.. redis.call('get','foo')
return key

然后测试代码如下

public class App 
{
    public static void main( String[] args )
    {
        String path = "lua/ceshi.lua";
        Jedis jedis = new Jedis("xx.xx.xx.xx", 6379);
        LuaToRedisDB luaToRedisDB = new LuaToRedisDB();
        byte[] key = luaToRedisDB.OpenLuaFile(path, jedis);
        System.out.println(luaToRedisDB.PerformLua(key, jedis));
    }
}

测试结果

bar
bar

 

你可能感兴趣的:(学习总结)