redistemplate事务实践

来源:互联网 发布:日语翻译精确的软件 编辑:程序博客网 时间:2024/05/20 04:49

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函数,而且是修改后的值,符合原理




隐患?!

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


 
原创粉丝点击