6.1 简介
Jedis 是 Redis 官方推荐的 java连接开发工具! 使用Java 操作Redis 中间件!
6.2 测试
-
导入依赖
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
-
测试连接
public class TestPing { public static void main(String[] args) { Jedis jedis = new Jedis("192.168.2.190",6379); System.out.println(jedis.ping()); } }
常用API与之前学习的指令一致
6.3 事务
public class TestTX {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.2.190", 6379);
jedis.flushDB();
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "world");
jsonObject.put("name", "qwe");
// 开启事务
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(); // 关闭连接
}
}
}