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

本文共 8586 字,大约阅读时间需要 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 中。

示例代码:

@Testpublic 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):获取哈希类型的单个字段值。

示例代码:

@Testpublic 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):弹出列表的最右边元素。

示例代码:

@Testpublic 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):计算两个集合的差集。

示例代码:

@Testpublic 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):遍历有序集合中的元素。

示例代码:

@Testpublic 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注入:

@Autowiredprivate RedisTemplate
redisCacheTemplate;

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

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

你可能感兴趣的文章
responded with a status of 404 ()
查看>>
吴恩达机器学习课程笔记(英文授课) Lv.1 新手村(回归)
查看>>
pair的用法
查看>>
SQL基本操作命令
查看>>
强制类型转换原理
查看>>
伪类选择器
查看>>
两正态总体参数的检验
查看>>
C# WinForm程序退出的方法
查看>>
ubuntu安装gem和fastlane
查看>>
ViroMedia集成android报错Lcom/facebook/react/bridge/WritableMap
查看>>
onFailure unexpected end of stream
查看>>
android 集成weex
查看>>
《C Prime Plus》(第六版) 第03章 编程练习 5 unsigned long int 格式化输出
查看>>
【echarts】中国地图china.js 在线引用地址
查看>>
Flex 布局的自适应子项内容过长导致其被撑大问题
查看>>
PL/SQL 动态Sql拼接where条件
查看>>
Lua-table 一种更少访问的安全取值方式
查看>>
虚函数
查看>>
菱形继承
查看>>
Error:Cannot read packageName from AndroidManifest.xml
查看>>