spring-redis相关jar版本:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.7.RELEASE</version>
</dependency>
在使用redisTemplate.keys(pattern);进行模糊查找时,发现A方法中能正常返回所有匹配到的数据,但B方法中一直返回空。debug之后在JedisConnection的
public Set<byte[]> keys(byte[] pattern) {
try {
if (this.isPipelined()) {
this.pipeline(new JedisResult(this.pipeline.keys(pattern)));
return null;
} else if (this.isQueueing()) {
this.transaction(new JedisResult(this.transaction.keys(pattern)));
return null;
} else {
return this.jedis.keys(pattern);
}
} catch (Exception var3) {
throw this.convertJedisAccessException(var3);
}
}
这个方法中发现,A方法能拿到值是因为管道isPipelined()和事务isQueueing()方法均为false,所以A方法拿值直接走
this.jedis.keys(pattern);
而B方法isQueueing()为true,此时走
this.transaction(new JedisResult(this.transaction.keys(pattern)));
所以如果B方法也想正常拿到匹配的keys,则需要将redis事务设为false。目前我的结果方案是在B方法取值前将事务关闭,取到值之后再将事务开启
/**
* 根据key匹配其下级所有的键
*
* @param pattern
* 键
* @return
*/
public Set<String> getKey(String pattern) {
try {
//关闭redis事务,事务开启无法模糊匹配
redisTemplate.setEnableTransactionSupport(false);
Set<String> keys = redisTemplate.keys(pattern);
//匹配到值后再开启事务,避免其余地方出错
redisTemplate.setEnableTransactionSupport(true);
return keys;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
这是初始化RedisTemplate时开启事务给自己留的坑,目前仅找到这种解决办法,如果有更好的解决方案,欢迎讨论