Redis 事务操作

1、RedisTemplate的API实现

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@EnableAutoConfiguration
@EnableFeignClients
//@ActiveProfiles("sonar")
//@Ignore
public class RedisTemplateTest {
    
    private static final Logger LOG = LoggerFactory.getLogger(RedisTemplateTest.class);
    
    @Autowired
    private RedisTemplate stringredisTemplate;


    @Before
    public void setUp() throws Exception {
    }
    
    @Test
    public void mutli() {
        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");
        System.out.println("junit-------------------------");
        System.out.println("----------------" + 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);//多重检测,直到执行成功。
    }
}

结果:

junit-------------------------
----------------[3, 3]

看看a的值:

2、RedisOperations

    @Test
    public void mutli2() throws InterruptedException {
        String key = "multThreadTest";
        
        stringredisTemplate.delete(key);
        
        Runnable runable = new Runnable() {
            @Override
            public void run() {
        
                stringredisTemplate.execute(new SessionCallback<Object>() {
                    @Override
                    @SuppressWarnings({ "unchecked", "rawtypes" })
                    public Object execute(RedisOperations operations) throws DataAccessException {
                        List<Object> result = null;
                        do {
                            int count = 0;
                            operations.watch(key);  // watch某个key,当该key被其它客户端改变时,则会中断当前的操作
                            String value = (String) operations.opsForValue().get(key);
                            if (!StringUtils.isNullOrEmpty(value)) {
                                count = Integer.parseInt(value);
                            }
                            count = count + 1;
                            operations.multi(); //开始事务
                            operations.opsForValue().set(key, String.valueOf(count));
                            try {
                                result = operations.exec(); //提交事务
                            } catch (Exception e) { //如果key被改变,提交事务时这里会报异常
        
                            }
                        } while (result == null); //如果失败则重试
                        return null;
                    }
        
                });
        
            }
        };
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(runable, "thread-" + (i + 1));
            thread.start();
            threads.add(thread);
        }
        
        for (Thread thread : threads) {
            thread.join();
        }
        
        Object value = stringredisTemplate.opsForValue().get(key);
        System.out.println(value);
    }

参考:

https://www.cnblogs.com/aoeiuv/p/6761688.html

https://my.oschina.net/sxwailyc/blog/1973427

原文地址:https://www.cnblogs.com/duanxz/p/14750040.html