Question

I am trying to multiply two numbers stored in Redis using the Lua Script. But I am getting ClassCastException. Could someone point out What is wrong in the program

jedis.set("one", "1");
jedis.set("two", "2");
String script = "return {tonumber(redis.call('get',KEYS[1])) * tonumber(redis.call('get',KEYS[2]))}";
String [] keys = new String[]{"one","two"};
Object response =  jedis.eval(script, 2, keys );
System.out.println(response);

throws

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to [B
    at redis.clients.jedis.Jedis.getEvalResult(Jedis.java:2806)
    at redis.clients.jedis.Jedis.eval(Jedis.java:2766)
    at com.test.jedis.script.SimpleScript.main(SimpleScript.java:18)
Était-ce utile?

La solution

You can't cast a table to a number in lua. What you want is to grab the number of elements in the table instead. You can do this by using the last element point #. Also, I'd highly recommend separating out your Lua script from the rest of your code, so it's cleaner. Your Lua script should look like:

local first_key = redis.call('get',KEYS[1])
local second_key = redis.call('get',KEYS[2])
return #first_key * #second_key

EDIT: Misunderstood the question. OP correctly pointed out he is trying to multiple two numbers stored as strings rather than a table length. In that case:

local first_key = redis.call('get',KEYS[1])
if not tonumber(first_key) then return "bad type on key[1]" end
local second_key = redis.call('get',KEYS[2])
if not tonumber(second_key) then return "bad type on key[2]" end
return tonumber(first_key) * tonumber(second_key)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top