什么是Jedis?
Jedis 是 Redis 官方推荐的 java 连接开发工具包! 使用 Java 操作 Redis 中间件!
Spring项目测试
- 导入对应的依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<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();
}
}
常用的API:
所有的api,对应于数据类型中的命令!
事务
package com.tuwer;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
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);
multi.exec();
}catch (Exception e){
multi.discard();
e.printStackTrace();
}finally {
System.out.println(jedis.get("u1"));
System.out.println(jedis.get("u2"));
jedis.close();
}
}
}
|