一般用try-catch-finally来处理事务
public class TestTX {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello","world");
jsonObject.put("name","KangKang");
String result = jsonObject.toJSONString();
Jedis jedis = new Jedis("云服务器ip", 6379); //填自己的就好
jedis.auth("reids密码"); //同上
jedis.flushAll();
System.out.println(jedis.ping());
//开启事务
Transaction multi = jedis.multi();
//使用try-catch来操作事务
try {
multi.set("key1",result);
multi.set("key2",result);
//提交事务
multi.exec();
} catch (Exception e) {
//如果出问题
multi.discard(); //放弃事务
e.printStackTrace();
}finally {
//关闭连接
System.out.println(jedis.get("key1"));
System.out.println(jedis.get("key2"));
jedis.close();
}
jedis.close();
}
}
模拟失败的代码
public class TestTX {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello","world");
jsonObject.put("name","KangKang");
String result = jsonObject.toJSONString();
Jedis jedis = new Jedis("云服务器ip", 6379); //填自己的云服务器ip或者localhost
jedis.auth("redis密码"); //填自己的redis密码
jedis.flushAll();
System.out.println(jedis.ping());
//开启事务
Transaction multi = jedis.multi();
try {
multi.set("key1",result);
multi.set("key2",result);
//模拟失败
int i = 1/0; //代码执行失败,抛出异常
//提交事务
multi.exec();
} catch (Exception e) {
//如果出问题
multi.discard(); //放弃事务
e.printStackTrace();
}finally {
//关闭连接
System.out.println(jedis.get("key1"));
System.out.println(jedis.get("key2"));
jedis.close();
}
jedis.close();
}
}



