spring-data-redis事务操作异常

相关jar

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.4.2</version>
        </dependency>

业务场景:
现有一个定时任务,将符合条件的新闻标题存入Reids,采用zset格式,新闻数据转换为json,试问时间为score,便于通过新闻时间分页获取数据。
执行定时任务时,先通过key删除原有的数据,然后批量增加新的数据,为了避免在删除命令执行后增加命令执行前会插入其他查询命令,导致查询结果为空,所以需要事物处理,以下代码:

    @Test
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void test001(){
        List<NewsInfo> list = getList("ztw_0707");
        Set<TypedTuple<String>> set = Sets.newHashSet();
        for (int i = 0; i < list.size(); i++) {
            String str = JSON.toJSONString(list.get(i), SerializerFeature.WriteMapNullValue);
            TypedTuple<String> typedTuple = new DefaultTypedTuple<String>(str, Double.valueOf(i));
            set.add(typedTuple);
        }
//      stringRedisTemplate.delete("myKey");
//      stringRedisTemplate.opsForZSet().add("myKet", set);
        Map<String, String> map = Maps.newHashMap();
        map.put("key001", "value001");
        map.put("key002", "value002");
        map.put("key003", "value003");
        SessionCallback<Object> sessionCallback = new SessionCallback<Object>(){
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                operations.multi();  
                operations.delete("test");
                //operations.opsForHash().putAll("test", map);
                operations.opsForZSet().add("test", set);
//              operations.opsForZSet().add("test", "value001", 1);
//              operations.opsForZSet().add("test", "value002", 2);
//              operations.opsForZSet().add("test", "value003", 3);
                //operations.opsForHash().put("test", "key001", "value001");
                operations.expire("test", 1, TimeUnit.HOURS);
                Object val=operations.exec();
                return val;
            }
        };
        try {
            Object obj = stringRedisTemplate.execute(sessionCallback); 
            System.out.println(obj.toString());
        } catch (Exception e) {
            System.out.println(e);
        }

    }

执行注释部分的代码没问题,唯但是operations.opsForZSet().add("test", set);时出现异常:
org.springframework.dao.InvalidDataAccessApiUsageException: Cannot use Jedis when in Multi. Please use JedisTransaction instead.; nested exception is redis.clients.jedis.exceptions.JedisDataException: Cannot use Jedis when in Multi. Please use JedisTransaction instead.

请教各位,怎么解决,或者有其它的好的解决方案。

1个回答

错误提示你了,要你直接用JedisTransaction,而不是用redis原生的multi来做事务

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐