数据库
首页 > 数据库> > spring-data-redis 事务操作

spring-data-redis 事务操作

作者:互联网

方法一:

@Autowired
    private RedisTemplate redisTemplate;


    /**
    * 事务方式一
    */
    @Test
    void testTransaction(){
        //开启事务支持   
        //记得开启事务支持,但是不知道为何,我已经开启了,结果还是出现“ ERR EXEC without MULTI”,找不到原因,可能是redis版本问题
        redisTemplate.setEnableTransactionSupport(true);
        //开启事务
        redisTemplate.multi();
        ValueOperations<String, String> stringops = redisTemplate.opsForValue();
        String key="test:transaction";
        stringops.set(key,"1");
        ListOperations<String, String> listOps = redisTemplate.opsForList();
        String key1="test:transaction2";
        listOps.leftPush(key1,"1111");
        System.out.println(stringops.get(key));
        System.out.println(listOps.range(key1, 0, 10));
        //执行事务
        redisTemplate.exec();
        System.out.println(stringops.get(key));
        System.out.println(listOps.range(key1, 0, 10));

    }

方法二:

/**
    * 执行事务方式二
     * 这种方式网友们比较推荐
    */
    @Test
    public void testTransaction2(){
        redisTemplate.execute(new SessionCallback<List<Object>>(){
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.opsForValue().set("name:1","walker11");
                operations.opsForValue().set("name:2","walker22");
                operations.opsForValue().set("name:3","walker33");
                return redisTemplate.exec();
            }
        });
    }

使用discard取消事务

 /**
    * 测试取消事务
    */
    @Test
    public void testDiscard(){
        Integer flag=1;
        redisTemplate.execute(new SessionCallback<List<Object>>(){
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.opsForValue().set("name:1","walker11");
                operations.opsForValue().set("name:2","walker22");
                operations.opsForValue().set("name:3","walker33");
                if(flag.equals(1)){
                    //取消事务,经测试,在使用discard之后,不能再次执行exec(),否则会出现 ERR EXEC without MULTI错误
                    redisTemplate.discard();
                    return null;
                }
                return redisTemplate.exec();
            }
        });
    }

 

标签:operations,事务,set,name,spring,opsForValue,redis,data,redisTemplate
来源: https://www.cnblogs.com/qianxiaoPro/p/16330010.html