源无极

导航

 

一、环境jdk8

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.2.RELEASE</version>
  <relativePath/>
</parent>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  常见的写法仍是采用 RedisTemplate 的默认配置,即不开启事务支持。

但是,我们可以通过使用 SessionCallback,

该接口保证其内部所有操作都是在同一个Session中

1.

  @Autowired
    private StringRedisTemplate redisTemplate;
  @GetMapping("/redis2")
    public void redisTran2() {
        SessionCallback<Object> sessionCallback = new SessionCallback<Object>() {
            @Override
            public  Object execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.opsForValue().set("h5", "dada");
                System.out.println("operations:h5的值事务前是:" + operations.opsForValue().get("h5"));
                System.out.println("redisTemplate:h5的值事务前是:" + redisTemplate.opsForValue().get("h5"));
                return operations.exec();
            }
        };
        System.out.println("redisTemplate:h5的值事务后1111是:" + redisTemplate.opsForValue().get("h5"));
        redisTemplate.execute(sessionCallback);
        System.out.println("redisTemplate:h5的值事务后2222是:" + redisTemplate.opsForValue().get("h5"));
    }
redisTemplate:h5的值事务后1111是:null
operations:h5的值事务前是:null
redisTemplate:h5的值事务前是:null
redisTemplate:h5的值事务后2222是:dada

 

执行redisTemplate.execute(sessionCallback);之后才会提交事务

我们在 SpringBoot 中操作 Redis 时,使用 RedisTemplate 的默认配置已经能够满足大部分的场景了。
如果要执行事务操作,使用 SessionCallback 是比较好,也是比较常用的选择

参考文章

 

posted on 2020-04-16 11:14  源无极  阅读(362)  评论(0)    收藏  举报