Jedis 连接 Redis 事务

public static void main(String[] args) {
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    jedis.flushDB();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("hello","world");
    jsonObject.put("name","zhangsan");

    // 开启事务
    Transaction multi = jedis.multi();

    String result = jsonObject.toJSONString();
    try {
        multi.set("user1",result);
        multi.set("user2",result);
        //int i = 1/0; // 模拟失败
        multi.exec(); // 执行事务
    } catch (Exception e) {
        multi.discard(); // 放弃事务
        e.printStackTrace();
    } finally {
        System.out.println(jedis.get("user1"));
        System.out.println(jedis.get("user2"));
        jedis.close(); // 关闭连接
    }
}
posted @ 2020-08-27 13:52  li修远  阅读(109)  评论(0编辑  收藏  举报