什么是Jedis?
Jedis 是 Redis 官方推荐的 java 连接开发工具包! 使用 Java 操作 Redis 中间件!
Spring项目测试
- 导入对应的依赖
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.1.1</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<!-- slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<!-- <scope>test</scope> -->
<scope>compile</scope>
</dependency>
- 编码测试
- 连接数据库(先启动redis-service)
- 操作命令
- 断开连接!
package com.tuwer;
import redis.clients.jedis.Jedis;
public class TestPing {
public static void main(String[] args) {
// 连接
Jedis jedis = new Jedis("localhost", 6379);
// 操作
System.out.println(jedis.ping());
// 断开连接
jedis.close();
// 关闭服务
//jedis.shutdown();
}
}
常用的API:
所有的api,对应于数据类型中的命令!
- String
- List
- Set
- Hash
- Zset
事务
package com.tuwer;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
/**
* @author 土味儿
* Date 2022/3/10
* @version 1.0
*/
public class TextTx {
public static void main(String[] args) {
// 连接
Jedis jedis = new Jedis("localhost", 6379);
// 清空数据
jedis.flushDB();
// 产生数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "world");
jsonObject.put("name", "tuwer");
String res = jsonObject.toJSONString();
// 开启事务
Transaction multi = jedis.multi();
try {
// 操作入列
multi.set("u1", res);
multi.set("u2", res);
// 异常
//int a = 1/0;
// 执行事务
multi.exec();
}catch (Exception e){
// 取消事务
multi.discard();
e.printStackTrace();
}finally {
// 输出
System.out.println(jedis.get("u1"));
System.out.println(jedis.get("u2"));
// 断开连接
jedis.close();
}
}
}