笔记内容来自B站博主《遇见狂神说》:Redis视频链接
小伙伴们可以熟悉一下本专栏的 Redis 文章,可以更好地理解
正常操作
package oldfe.study;import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;public class Main {public static void main(String[] args) {Jedis jedis = new Jedis("127.0.0.1", 6379);jedis.auth("123456");jedis.flushDB();JSONObject jsonObject = new JSONObject();jsonObject.put("name", "叫我OldFe");jsonObject.put("age", 16);String result = jsonObject.toJSONString();// 开启事务Transaction multi = jedis.multi();try {multi.set("info", result);multi.set("info1", result);multi.exec(); // 执行事务} catch (Exception e) {multi.discard(); // 放弃事务e.printStackTrace();} finally {System.out.println("info=" + jedis.get("info"));System.out.println("info1=" + jedis.get("info1"));jedis.close(); // 关闭连接}}
}
// 输出:
info={"name":"叫我OldFe","age":16}
info1={"name":"叫我OldFe","age":16}
执行异常
package oldfe.study;import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;public class Main {public static void main(String[] args) {Jedis jedis = new Jedis("118.89.55.144", 6388);jedis.auth("Redis@2024");jedis.flushDB();JSONObject jsonObject = new JSONObject();jsonObject.put("name", "叫我OldFe");jsonObject.put("age", 16);String result = jsonObject.toJSONString();// 开启事务Transaction multi = jedis.multi();try {multi.set("info", result);multi.set("info1", result);int i = 2 / 0; // 代码抛出异常事务,执行失败multi.exec(); // 执行事务} catch (Exception e) {multi.discard(); // 放弃事务e.printStackTrace();} finally {System.out.println("info=" + jedis.get("info"));System.out.println("info1=" + jedis.get("info1"));jedis.close(); // 关闭连接}}
}
// 输出:
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
java.lang.ArithmeticException: / by zeroat oldfe.study.Main.main(Main.java:24)
info=null
info1=null
下一篇:《【从0到1进阶Redis】SpringBoot整合Redis》更新中。。。