正常情况下

package com.luoyufeng;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestTX {

    public static void main(String[] args) {

        Jedis jedis = new Jedis("你的ip",6379);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","luoyufeng");

        Transaction multi = jedis.multi(); // 开启事务
        String result = jsonObject.toJSONString();
        try {
            multi.set("user1",result);
            multi.set("user2",result);
            multi.exec();
        } catch (Exception e) {
            multi.discard(); // 放弃事务
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close(); // 关闭连接
        }
    }
}

不正常情况

package com.luoyufeng;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestTX {

    public static void main(String[] args) {

        Jedis jedis = new Jedis("你的ip",6379);

        jedis.flushDB();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","luoyufeng");

        Transaction multi = jedis.multi(); // 开启事务
        String result = jsonObject.toJSONString();

        try {
            multi.set("user1",result);
            int i = 1 / 0; // 代码抛出异常事务,执行失败
            multi.set("user2",result);
            multi.exec();
        } catch (Exception e) {
            multi.discard(); // 放弃事务
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close(); // 关闭连接
        }
    }
}

最后修改:2021 年 03 月 12 日
如果觉得我的文章对你有用,请随意赞赏