首页 > 代码库 > Spring RedisTemplate操作-事务操作(9)

Spring RedisTemplate操作-事务操作(9)

@Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, String> stringredisTemplate;

    public void flushdb() {
        stringredisTemplate.execute(new RedisCallback<Object>() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }

//    @Transactional           //哪怕加了这个注解spring的配置文件里redistemplate配置也要开启事务支持
    public void mutli() {
        flushdb();
        ValueOperations<String, String> vo = stringredisTemplate.opsForValue();
        stringredisTemplate.setEnableTransactionSupport(true);

        stringredisTemplate.multi();
        vo.set("b", "1");
        vo.increment("b", 2);
        vo.get("b");
        stringredisTemplate.discard();

        stringredisTemplate.multi();
        vo.set("a", "1");
        vo.increment("a", 2);
        vo.get("a");
        out(stringredisTemplate.exec());
        // System.out.println("-------");
        
        stringredisTemplate.setEnableTransactionSupport(false);
        List<Object> rs = null;
        do{
            stringredisTemplate.watch("a");
            stringredisTemplate.multi();
            vo.increment("a", 2);
            vo.increment("a", 2);
            rs = stringredisTemplate.exec();
        }while(rs == null);//多重检测,直到执行成功。
        
        
        
    }

    public void out(String str) {
        System.out.println(str);
    }

    public void out(Collection list) {
        System.out.println(list);
    }

    public void out(long num) {
        System.out.println(num);
    }

    public void out(boolean num) {
        System.out.println(num);
    }

    public void out(DataType num) {
        System.out.println(num);
    }

 

Spring RedisTemplate操作-事务操作(9)