• redistemplate事务实践


    code:

        public Object testRedisMulti() {
    
            Object o = stringRedisTemplate.execute(new SessionCallback() {
                @Override
                public Object execute(RedisOperations operations) throws DataAccessException {
                 //   operations.watch("testRedisMulti");
                    operations.multi();
                    operations.opsForValue().set("testRedisMulti", "0");
                    String now = (String) operations.opsForValue().get("testRedisMulti");
                    System.out.println(now);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    now = (String) operations.opsForValue().get("testRedisMulti");
                    System.out.println(now);
                    Object rs = operations.exec();
                    return rs;
                }
            });
    
            System.out.println(o);
    
            return o;
        }



    初始值:

    127.0.0.1:6389> get testRedisMulti

    "initial"

    代码执行:

                    operations.multi();
                    operations.opsForValue().set("testRedisMulti", "0");
                    String now = (String) operations.opsForValue().get("testRedisMulti");
                    System.out.println(now);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

    客户端:

    127.0.0.1:6389> get testRedisMulti

    "initial",意味着multi中的命令还未发送

    System.out输出:

    null


    注意在multi中的get是娶不到值的

    过5秒。。。

    代码执行:

    now = (String) operations.opsForValue().get("testRedisMulti");
                    System.out.println(now);
                    Object rs = operations.exec();
                    return rs;

    System.out输出:

    null
     

    客户端:

    127.0.0.1:6389> get testRedisMulti

    "0",multi命令提交后修改了值

     

    最终输出

     

    [0, 0]



    可以看到两次get的值返回给了execute函数,而且是修改后的值,符合原理

    初始化 initial

    redis写0

    redis读 null

    redis提交0

    redis读 null

    回调读[0,0]

    隐患?!

    Sping Data Redis 使用事务时,不关闭连接的问题

    
    
    
    
  • 相关阅读:
    动态规划最后一击
    leetcode N-Queens I && N-Queens II
    leetcode Spiral Matrix
    leetcode Submission Details
    由网易云音乐到算法体会
    leetcode Rotate Image
    线性表之双链表
    线性表之循环单链表
    线性表之单链表
    [HDU] 1561 The more, The Better 树形DP加01分组背包
  • 原文地址:https://www.cnblogs.com/silyvin/p/9106722.html
Copyright © 2020-2023  润新知