jedis操作redis事务练习

jedis操作redis实现事务:

 

package com.zyq.practise;

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

/**
 * Created by yyyy on 2020/9/16.
 */
public class TestMulti {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();

        //创建json格式的字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","yyy");
        String result = jsonObject.toJSONString();

        //开启事务
        Transaction multi = jedis.multi();
        try{
            //redis中存入一条数据
            multi.set("json1",result);
            //在存入一条数据
            multi.set("json2",result);
            //异常模拟
            int i=1/0;
            multi.exec();
        }catch (Exception e){
            multi.discard();//放弃执行
            e.printStackTrace();
        }finally {
            System.out.println("============="+jedis.get("json1"));
            System.out.println("============="+jedis.get("json2"));
            //最终,关闭客户端
            jedis.close();
        }

    }
}

 

正常执行:

============={"name":"yyy","hello":"world"}

============={"name":"yyy","hello":"world"}

发生异常时候的执行结果:

java.lang.ArithmeticException: / by zero

at com.zyq.practise.TestMulti.main(TestMulti.java:30)

=============null

=============null

posted on 2020-10-03 15:33  ~码铃薯~  阅读(220)  评论(0编辑  收藏  举报

导航