Redis——事务

一、Redis事务在redis-cli中使用:

  1)开启事务:multi

  2)提交事务:exec

  3)取消事务:discard

  4)示例:

    

  5)注意:redis事务中,如果指令的格式正确,数据类型不正确,报错后不会回滚;

    

  6)redis中的锁:

    1、悲观锁;

    2、乐观锁:操作时候别人也可以操作,但是提交时候会判断,如果被操作了,则无法提交;

      1)watch:监控一个key;unwatch:清除;

        

      

    //ABA问题:A操作事务,B在A提交前操作了A中的数据,导致A事务提交失败;

二、Redis事务在spring-data-redis使用:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:redis.xml")
public class RedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){
        redisTemplate.execute(new SessionCallback(){
            public Object execute(RedisOperations operations) throws DataAccessException {
                // 开启事务
                operations.multi();
                operations.opsForValue().set("name","zs");
                System.out.println(operations.opsForValue().get("name"));
                // 提交事务
                operations.exec();
                
                System.out.println(operations.opsForValue().get("name"));
                return null;
            }
        });
    }
}

 

posted @ 2019-08-01 20:50  开拖拉机的拉风少年  阅读(127)  评论(0编辑  收藏  举报