跳到主要内容

执行命令

使用 JdbcTemplate 可以直接执行 Redis 命令并进行读写数据操作,在此之前请确保已经正确配置好 Redis 数据源,具体请参考 Redis 驱动使用指南

提示

更多使用方式请参考 JdbcTemplate 类,在使用过程中下面两个特性由于驱动原因无法支持:

  • 批量化
  • 存储过程

JdbcTemplate 接口

定义 JdbcTemplate,使用创建好的 DataSource 或 Connection 作为参数传入。

创建 JdbcTemplate
// 2,创建 Session
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
或者
JdbcTemplate jdbc = new JdbcTemplate(connection);

Key 读/写/删

读取 Key
// 直接命令方式
String result1 = jdbc.queryForString("GET myKey");
// 参数化命令方式
String result2 = jdbc.queryForString("GET ?", "myKey");
写入 Key
// 直接命令方式
int result1 = jdbc.executeUpdate("SET myKey myValue");
// 参数化命令方式
int result2 = jdbc.executeUpdate("SET ? ?", new Object[] { "myKey", "myValue" });
删除 Key
// 直接命令方式
int result1 = jdbc.executeUpdate("DEL myKey");
// 参数化命令方式
int result2 = jdbc.executeUpdate("DEL ?", "myKey");

Key 读/写/删 (多个 Key)

读取多个 Key
// 直接命令方式
Map<String, Integer> result1= jdbc.queryForPairs("MGET key1 key2 key3", String.class, Integer.class);
// 参数化命令方式
Map<String, Integer> result2 = jdbc.queryForPairs("MGET ? ? ?", String.class, Integer.class, new Object[] { "key1", "key2", "key3" });
写入多个 Key
// 直接命令方式
int result1 = jdbc.executeUpdate("MSET key1 123 key2 456 key3 789");
// 参数化命令方式
int result2 = jdbc.executeUpdate("MSET ? ? ? ? ? ?", new Object[] { "key1", "value1", "key2", "value2", "key3", "value3" });
删除多个 Key
// 直接命令方式
int result1 = jdbc.executeUpdate("DEL key1 key2 key3");
// 参数化命令方式
int result2 = jdbc.executeUpdate("DEL ? ? ?", new Object[] { "key1", "key2", "key3" });

对象的 读/写/删

使用 @BindTypeHandler 注解绑定 JSON 序列化
@BindTypeHandler(JsonTypeHandler.class)
public class MyObject {
...
}
读取对象
// 直接命令方式
MyObject result1 = jdbc.queryForObject("GET myObjectKey", MyObject.class);
// 参数化命令方式
MyObject result2 = jdbc.queryForObject("GET ?", MyObject.class, "myObjectKey");
写入对象
// 参数化命令方式
int result1 = jdbc.executeUpdate("SET ? ?", new Object[] { "myObjectKey", (MyObject) myObject });
删除对象
// 直接命令方式
int result1 = jdbc.executeUpdate("DEL myObjectKey");
// 参数化命令方式
int result2 = jdbc.executeUpdate("DEL ?", "myObjectKey");

支持的命令

完整的 Redis 命令支持性可参考 支持的命令列表