Spring RedisTemplate操作-事务操作

package com.panku.web.redis;
import java.util.Collection;
import java.util.List;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
 * Spring RedisTemplate操作-事务操作
 * @author ccx
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = "classpath:applicationContext.xml")  
public class RedisTemplateTransactional {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate stringredisTemplate;

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

    @Transactional           //哪怕加了这个注解spring的配置文件里redistemplate配置也要开启事务支持
    public void mutli() {
        flushdb();
        ValueOperations 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 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操作-事务操作)