Jedis 使用
Redis系列笔记跟着B站up狂神说学习,所有笔记照着敲了一遍,记录下来供后续忘了参考。
一、NoSQL简介
二、Redis入门–配置安装等
三、Redis数据类型(重要)
四、Redis事务
五、Jedis使用
六、SpringBoot整合Redis
七、Redis持久化
使用Java来操作Redis
1、导入maven依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- 按需导入-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
</dependencies>
2、编码测试
- 连接数据库
- 操作命令
- 断开连接
public class TestPing {
public static void main(String[] args) {
// new jedis 对象
Jedis jedis = new Jedis("127.0.0.1", 6379);
// jedis 所有的命令就是Redis上的所有命令
System.out.println(jedis.ping());
}
}
// 输出: PONG
常用API(上面API)
所有的命令,就是上面完全一样的命令
// new jedis 对象
Jedis jedis = new Jedis("127.0.0.1", 6379);
// jedis 所有的命令就是Redis上的所有命令
System.out.println("清空数据:" + jedis.flushDB());
System.out.println("新增kv键值对:" + jedis.set("username", "huagege"));
System.out.println("新增kv键值对:" + jedis.set("password", "123456"));
Set<String> keys = jedis.keys("*");
System.out.println(keys);
输出:
清空数据:OK
新增kv键值对:OK
新增kv键值对:OK
[password, username]
事务
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "world");
jsonObject.put("name", "huage");
jsonObject.put("password", "123456");
Transaction multi = jedis.multi();
String s = jsonObject.toJSONString();
try {
multi.set("user1", s);
multi.set("user2", s);
multi.exec(); // 执行事务
} catch (Exception e) {
multi.discard(); // 失败放弃事务
e.printStackTrace();
} finally {
System.out.println(jedis.get("user1"));
System.out.println(jedis.get("user2"));
jedis.close(); // 关闭redis
}
}
/*************************/
// 输出
{"password":"123456","name":"huage","hello":"world"}
{"password":"123456","name":"huage","hello":"world"}