Java实现redis事务

来源:互联网 发布:ta热分析软件 编辑:程序博客网 时间:2024/05/16 11:10

1.  正常执行的事务

    @Test    public void test() {        Jedis jedis = new Jedis("localhost");        Transaction transaction = jedis.multi();        transaction.lpush("key", "11");        transaction.lpush("key", "22");          transaction.lpush("key", "33");        List<Object> list = transaction.exec();    }
上述事务正常执行,执行完后,再执行

System.out.println(jedis.lrange("key",0,10));
会将上述事务中插入redis中的数据全部打印出来


2. 执行事务的过程中抛出异常

    @Test    public void test() {        Jedis jedis = new Jedis("localhost");        try {            Transaction transaction = jedis.multi();            transaction.lpush("key", "11");            transaction.lpush("key", "22");            int a = 6 / 0;            transaction.lpush("key", "33");            List<Object> list = transaction.exec();        } catch (Exception e) {        }    }
上述代码执行事务的过程中会抛出异常,导致事务失败,所以全部无效,再执行

System.out.println(jedis.lrange("key",0,10));
打印出的结果为空

结论: 事务要么全部执行成功,要么全部不执行


1 0
原创粉丝点击