博客
关于我
SpringBoot使用RedisTemplate简单操作Redis的五种数据类型
阅读量:571 次
发布时间:2019-03-10

本文共 8683 字,大约阅读时间需要 28 分钟。

Spring RedisTemplate 常用操作指南

1. 操作字符串类型

RedisTemplate 提供了 opsForValue() 方法来操作字符串类型。常用的方法包括:

  • set(key, value):将值存入 Redis 中。例如:
redisTemplate.opsForValue().set("Stringkey1", "StringValue1");
redisTemplate.opsForValue().set("Stringkey2", "StringValue2", 120, TimeUnit.SECONDS);
  • get(key):获取存储在 Redis 中的字符串值。
  • getAndSet(key, value):获取旧值并将新值存入 Redis 中。

示例代码:

@Test
public void test1() {
init();
redisTemplate.opsForValue().set("Stringkey1", "StringValue1");
redisTemplate.opsForValue().set("Stringkey2", "StringValue2", 120, TimeUnit.SECONDS);
System.out.println(redisTemplate.opsForValue().get("Stringkey1"));
System.out.println(redisTemplate.opsForValue().get("Stringkey2"));
redisTemplate.opsForValue().getAndSet("Stringkey1", "StringValue11");
System.out.println(redisTemplate.opsForValue().get("Stringkey1"));
}

2. 操作哈希类型

Redis 的哈希类型适合存储结构化的对象,支持嵌套字段操作。opsForHash() 提供了以下方法:

  • putAll(key, map):将映射表存入 Redis 中。
  • put(key, hashKey, value):存入单个字段。
  • entries(key):获取整个哈希类型的键值对。
  • get(key, hashKey):获取哈希类型的单个字段值。

示例代码:

@Test
public void test3() {
init();
HashMap
map = new HashMap<>();
map.put("id", "1");
map.put("name", "LiuShihao");
map.put("age", "24");
map.put("job", "Police");
redisTemplate.opsForHash().putAll("userHash", map);
System.out.println(redisTemplate.opsForHash().entries("userHash"));
redisTemplate.opsForHash().put("userHash2", "id", "1");
redisTemplate.opsForHash().put("userHash2", "name", "aaa");
redisTemplate.opsForHash().put("userHash2", "age", "24");
redisTemplate.opsForHash().put("userHash2", "job", "美团外卖");
System.out.println(redisTemplate.opsForHash().get("userHash2", "id"));
System.out.println(redisTemplate.opsForHash().get("userHash2", "name"));
System.out.println(redisTemplate.opsForHash().get("userHash2", "age"));
System.out.println(redisTemplate.opsForHash().get("userHash2", "job"));
System.out.println(redisTemplate.opsForHash().keys("userHash2"));
System.out.println(redisTemplate.opsForHash().values("userHash2"));
}

3. 操作列表类型

Redis 列表适合用于消息队列或有序数据的存储。opsForList() 提供了以下操作:

  • leftPushAll(key, array):向列表中批量插入元素。
  • rightPush(key, value):向列表中插入单个元素。
  • range(key, start, end):获取列表中从起始索引到结束索引的元素。
  • index(key, index):获取列表中指定索引的元素。
  • leftPop(key):弹出列表的最左边元素。
  • rightPop(key):弹出列表的最右边元素。

示例代码:

@Test
public void test2() {
init();
String[] user1 = new String[]{"1", "zs", "19", "程序员"};
redisTemplate.opsForList().leftPushAll("user1-leftPushAll", user1);
redisTemplate.opsForList().rightPushAll("user1-rightPushAll", user1);
System.out.println(redisTemplate.opsForList().range("user1-leftPushAll", 0, -1));
System.out.println(redisTemplate.opsForList().range("user1-rightPushAll", 0, -1));
redisTemplate.opsForList().rightPush("user2-rightPush", "1");
redisTemplate.opsForList().rightPush("user2-rightPush", "ls");
redisTemplate.opsForList().rightPush("user2-rightPush", "20");
redisTemplate.opsForList().rightPush("user2-rightPush", "教师");
System.out.println(redisTemplate.opsForList().index("user2-rightPush", 0));
System.out.println(redisTemplate.opsForList().index("user2-rightPush", 1));
System.out.println(redisTemplate.opsForList().index("user2-rightPush", 2));
System.out.println(redisTemplate.opsForList().index("user2-rightPush", 3));
String[] user3 = new String[]{"3", "ww", "28", "警察"};
redisTemplate.opsForList().rightPushAll("user3", user3);
System.out.println(redisTemplate.opsForList().range("user3", 0, -1));
System.out.println(redisTemplate.opsForList().rightPop("user3"));
System.out.println(redisTemplate.opsForList().range("user3", 0, -1));
}

4. 操作集合类型

Redis 集合类型适合存储不重复的值,支持交集、并集、差集等操作。opsForSet() 提供了以下方法:

  • add(key, values):将一个或多个元素添加到集合中。
  • members(key):获取集合中的所有元素。
  • remove(key, values):移除集合中的一个或多个元素。
  • scan(key, scanOptions):遍历集合中的元素。
  • intersect(key1, key2):计算两个集合的交集。
  • union(key1, key2):计算两个集合的并集。
  • difference(key1, key2):计算两个集合的差集。

示例代码:

@Test
public void test4() {
init();
String[] citys = new String[]{"北京", "上海", "广州", "深圳"};
redisTemplate.opsForSet().add("citySet", citys);
System.out.println(redisTemplate.opsForSet().members("citySet"));
redisTemplate.opsForSet().add("citySet", "郑州", "北京", "上海");
System.out.println(redisTemplate.opsForSet().members("citySet"));
System.out.println(redisTemplate.opsForSet().remove("citySet", "广州"));
System.out.println(redisTemplate.opsForSet().members("citySet"));
Cursor citySet = redisTemplate.opsForSet().scan("citySet", ScanOptions.NONE);
while (citySet.hasNext()) {
System.out.println(citySet.next());
}
redisTemplate.opsForSet().add("CitysSet1", "北京", "武汉", "石家庄", "郑州", "西安", "济南");
redisTemplate.opsForSet().add("CitysSet2", "上海", "浙江", "南京", "郑州", "香港", "北京");
redisTemplate.opsForSet().intersectAndStore("CitysSet1", "CitysSet2", "CitysSetIntersectAndStore");
redisTemplate.opsForSet().unionAndStore("CitysSet1", "CitysSet2", "CitysSetUnionAndStore");
redisTemplate.opsForSet().differenceAndStore("CitysSet1", "CitysSet2", "CitysSetDifferenceAndStore");
System.out.println(redisTemplate.opsForSet().members("CitysSetIntersectAndStore"));
System.out.println(redisTemplate.opsForSet().members("CitysSetUnionAndStore"));
System.out.println(redisTemplate.opsForSet().members("CitysSetDifferenceAndStore"));
}

5. 操作有序集合类型

Redis 有序集合结合了集合和排序功能,opsForZSet() 提供了以下操作:

  • add(key, tuple):将有序集合中的元素及其分数值存入。
  • remove(key, values):移除有序集合中的一个或多个元素。
  • range(key, start, end):获取有序集合中按分数值排序的元素。
  • rangeByScore(key, min, max):根据分数值范围获取有序集合中的元素。
  • rank(key, value):获取指定元素在有序集合中的排名。
  • size(key):获取有序集合的成员数。
  • scan(key, scanOptions):遍历有序集合中的元素。

示例代码:

@Test
public void test5() {
ZSetOperations.TypedTuple
objectTypedTuple1 = new DefaultTypedTuple<>("肖申克的救赎", 9.7);
ZSetOperations.TypedTuple
objectTypedTuple2 = new DefaultTypedTuple<>("霸王别姬", 9.6);
ZSetOperations.TypedTuple
objectTypedTuple3 = new DefaultTypedTuple<>("阿甘正传", 9.5);
ZSetOperations.TypedTuple
objectTypedTuple4 = new DefaultTypedTuple<>("这个杀手不太冷", 9.4);
ZSetOperations.TypedTuple
objectTypedTuple5 = new DefaultTypedTuple<>("冷血狂宴 / 帮派2", 4.0);
Set
> movie = new HashSet<>(); movie.add(objectTypedTuple1); movie.add(objectTypedTuple2); movie.add(objectTypedTuple3); movie.add(objectTypedTuple4); movie.add(objectTypedTuple5); redisTemplate.opsForZSet().add("movie", movie); System.out.println(redisTemplate.opsForZSet().range("movie", 0, -1)); redisTemplate.opsForZSet().add("StudentZSet", "99", 9.9); redisTemplate.opsForZSet().add("StudentZSet", "80", 8.0); redisTemplate.opsForZSet().add("StudentZSet", "69", 6.9); redisTemplate.opsForZSet().add("StudentZSet", "52", 5.4); redisTemplate.opsForZSet().add("StudentZSet", "32", 3.4); redisTemplate.opsForZSet().add("StudentZSet", "23", 1.9); System.out.println(redisTemplate.opsForZSet().range("StudentZSet", 0, -1)); redisTemplate.opsForZSet().remove("StudentZSet", "69"); System.out.println(redisTemplate.opsForZSet().range("StudentZSet", 0, -1)); System.out.println(redisTemplate.opsForZSet().rank("movie", "阿甘正传")); System.out.println(redisTemplate.opsForZSet().rangeByScore("StudentZSet", 3, 8)); System.out.println("分数在0至8区间内的成员个数:" + redisTemplate.opsForZSet().count("StudentZSet", 3, 8)); System.out.println("movie有序集合的成员数:" + redisTemplate.opsForZSet().size("movie")); System.out.println("获取指定成员的score值:" + redisTemplate.opsForZSet().score("movie", "这个杀手不太冷")); Cursor cursor = redisTemplate.opsForZSet().scan("movie", ScanOptions.NONE); while (cursor.hasNext()) { ZSetOperations.TypedTuple
next = cursor.next(); System.out.println(next.getValue() + " 的分数值:" + next.getScore()); } }

RedisTemplate 初始化

在应用启动时,确保RedisTemplate 初始化完成。可以通过自定义初始化方法设置序列化器:

@Component
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheConfig {
@Bean
public RedisTemplate
redisCacheTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate
redisTemplate = new RedisTemplate<>();
RedisSerializer redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setValueSerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
redisTemplate.setHashValueSerializer(redisSerializer);
redisTemplate.setConnectionFactory(connectionFactory);
System.out.println("RedisTemplate加载...");
return redisTemplate;
}
}

使用说明

在需要使用RedisTemplate的地方,通过Autowired注入:

@Autowired
private RedisTemplate
redisCacheTemplate;

通过上述方法,可以方便地操作 Redis 中的五种数据类型。

转载地址:http://ltuvz.baihongyu.com/

你可能感兴趣的文章
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm scripts 使用指南
查看>>
npm should be run outside of the node repl, in your normal shell
查看>>
npm start运行了什么
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
npm 下载依赖慢的解决方案(亲测有效)
查看>>
npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
查看>>