代码当中使用RedisTemplate操作String、List都是正常的,但是操作zadd就会报错,有人说是这两个依赖的版本不一致的问题,但是项目中还有其他地方要用到,所以改版本号行不通,
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.3</version>
</dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/>
下面是我操作的核心代码
@Resource
private RedisTemplate<String, String> redisTemplate;
public void enqueue(String queueName, String element) {
log.info("ZSetQueueManager enqueue start,queueName:{},element:{}", queueName, element);
long timeMillis = System.currentTimeMillis();
try {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
ZSetOperations<String, String> opsForZSet = redisTemplate.opsForZSet();
opsForZSet.add(queueName, element, timeMillis);
log.info("ZSetQueueManager enqueue end,queueName:{},element:{}", queueName, element);
} catch (Exception e) {
log.error("ZSetQueueManager enqueue error,queueName:{},element:{}", queueName, element, e);
}
}
起初我认为是版本号不一致的问题,因为线上服务器是7.0,本地是5.0,但是一推敲发现不成立,zadd操作应该哪个版本都支持的,所以我排除了这种想法
解决方案:
改用Redisson
@Resource
private Redisson redissonClient;
public void enqueue(String queueName, String element) {
log.info("ZSetQueueManager enqueue start,queueName:{},element:{}", queueName, element);
long timeMillis = System.currentTimeMillis();
try {
// RScoredSortedSet<Object> scoredSortedSet = redissonClient.getScoredSortedSet(queueName);
// scoredSortedSet.add(0, element);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
ZSetOperations<String, String> opsForZSet = redisTemplate.opsForZSet();
opsForZSet.add(queueName, element, timeMillis);
log.info("ZSetQueueManager enqueue end,queueName:{},element:{}", queueName, element);
} catch (Exception e) {
log.error("ZSetQueueManager enqueue error,queueName:{},element:{}", queueName, element, e);
}
}