当我像下面的代码一样使用jedis时:
public class JedisTest extends Sync {
private static final String _SET_KEY_1 = "test1";
private static final String _SET_KEY_2 = "test2";
public void process() throws SQLException {
Set<String> appSet = getAllUserableAppkey();
final ShardedJedis jedis = RedisHelper.getJedis();
final ShardedJedisPipeline pipeline = jedis.pipelined();
for (String key : appSet) {
Set<String> result = jedis.smembers(_SET_KEY_1);
Set<String> result2 = jedis.smembers(_SET_KEY_2);
String rangName = String.format("%s::%s", "test", key);
for (int i = 0; i < 10; i++) {
pipeline.sadd(rangName, String.valueOf(i));
}
}
pipeline.sync();
}
public Set<String> getAllUserableAppkey() {
}
public static void main(String[] args) throws Exception {
DbHelper.init();
RedisHelper.init();
JedisTest jedisTest = new JedisTest();
try {
jedisTest.process();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
它抛出这样的异常:
Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List
at redis.clients.jedis.Connection.getBinaryMultiBulkReply(Connection.java:224)
at redis.clients.jedis.Connection.getMultiBulkReply(Connection.java:217)
at redis.clients.jedis.Jedis.smembers(Jedis.java:1055)
at redis.clients.jedis.ShardedJedis.smembers(ShardedJedis.java:339)
at com.snda.sync.impl.test.JedisTest.process(JedisTest.java:29)
at com.snda.sync.impl.test.JedisTest.main(JedisTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
我可以修改代码来纠正,如:
public void process() throws SQLException {
Set<String> appSet = getAllUserableAppkey();
final ShardedJedis jedis = RedisHelper.getJedis();
for (String key : appSet) {
final ShardedJedisPipeline pipeline = jedis.pipelined();
Set<String> result = jedis.smembers(_SET_KEY_1);
Set<String> result2 = jedis.smembers(_SET_KEY_2);
//log.warn("result1 :{},result2:{}",result,result2);
String rangName = String.format("%s::%s", "test", key);
for (int i = 0; i < 10; i++) {
pipeline.sadd(rangName, String.valueOf(i));
}
pipeline.sync();
}
}
但是我不知道为什么异常抛出,pipline.sadd()
与jedis.smembers
发生冲突?
谢谢你回答我!
jedis是最新的:2.7.2
答案 0 :(得分:2)
管道传输时不应直接使用Jedis实例。
Pipeline使用Jedis实例'流(不初始化新流),并且由于正常操作立即读取响应并且管道稍后读取整个响应,因此混合两个用法会使Jedis陷入麻烦。
P - 流水线/ N - 正常
请求 - &gt; P(1)P(2)N(3)N(4)P(5)
Redis响应 - &gt; P(1)P(2)N(3)N(4)P(5)
匹配的请求 - 响应 - &gt; N(1:应为3)N(2:应为4)P(3:应为1)P(4:应为2)P(5)
你可以看到回应很容易出现问题。