You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redisson调用Redis函数出现编码异常,参数解析失败求助

Redis函数Java调用编码乱码问题解决

问题场景

注册的Redis函数代码:

redis.register_function('eval_resources', function(keys, args)
    return type(args[1]) .. " " .. args[1]
end)

Java调用代码:

Object[] argsList = {"123", "abc"};
String res2 = function.call(
        FunctionMode.WRITE,
        "eval_resources",
        FunctionResult.STRING,
        Collections.emptyList(),
        argsList);

调用后得到响应string 12�,Lua中无法将参数解析为整数,即使截取字符也失败,但使用redis-cli调用该函数一切正常。

解决方法

  • 统一编码配置:确保Java客户端与Redis服务器使用相同编码(推荐UTF-8)。若使用Jedis客户端,创建连接时可指定编码:
    new Jedis(host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, true, null, null, StandardCharsets.UTF_8);
    
  • 传递字节数组替代字符串:Java端将字符串转为UTF-8字节数组后传递,修改参数列表:
    Object[] argsList = {"123".getBytes(StandardCharsets.UTF_8), "abc".getBytes(StandardCharsets.UTF_8)};
    
    同时在Lua函数中显式转换为字符串:
    redis.register_function('eval_resources', function(keys, args)
        local arg1 = tostring(args[1])
        local numericalVal = tonumber(arg1)
        return type(arg1) .. " " .. arg1 .. " type of num ->" .. type(numericalVal)
    end)
    
  • 升级客户端版本:检查所用Java Redis客户端(如Jedis、Lettuce)是否存在函数调用的编码bug,尝试升级至最新稳定版本。
  • Lua端清理无效字符:若仍有乱码残留,可在Lua中过滤非数字字符后再转整数:
    redis.register_function('eval_resources', function(keys, args)
        local cleaned = string.gsub(args[1], "%D", "")
        local numericalVal = tonumber(cleaned)
        return "cleaned: " .. cleaned .. " num type: " .. type(numericalVal)
    end)
    

内容的提问来源于stack exchange,提问作者siddharthabhi30

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:54:57