Redis数据类型与相关使用场景
前言
Redis数据类型一共8种,其中广为人知的有5种:
string、list、set、zset和hash
另外,还有3种特殊的数据类型:
Geospacial、hyperloglog和bitmap
1.string
string类型可以用作计数器,比如博客访问量,因为redis在计算时是单线程的,所以线程是绝对安全的:
1 2 3 4 5 6 7 8 9 | /** * 自增时只能是整数和整数相加,或者浮点数和浮点数相加,不能整数和浮点数混淆 */ public void comput() { stringRedisTemplate.opsForValue().set( "number" , "5.2" ); stringRedisTemplate.opsForValue().increment( "number" , 1.0 ); stringRedisTemplate.opsForValue().increment( "number" , 1.0 ); System.out.println(stringRedisTemplate.opsForValue().get( "number" )); } |
2.list
list具有有序的特点,可以用于实现简单的消息队列:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * 实现简单的消息队列功能,记得初始化时要清空 */ public void list() { stringRedisTemplate.opsForList().getOperations().delete( "arr" ); stringRedisTemplate.opsForList().leftPush( "arr" , "1" ); stringRedisTemplate.opsForList().leftPush( "arr" , "2" ); stringRedisTemplate.opsForList().leftPush( "arr" , "3" ); stringRedisTemplate.opsForList().leftPush( "arr" , "4" ); stringRedisTemplate.opsForList().rightPop( "arr" ); System.out.println(stringRedisTemplate.opsForList().rightPop( "arr" )); System.out.println(stringRedisTemplate.opsForList().rightPop( "arr" )); System.out.println(stringRedisTemplate.opsForList().rightPop( "arr" )); } |
3.set
set可以进行交集、并集、补集和差集等操作,可以用于找 公共好友:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //首先数据清空 <br> stringRedisTemplate.opsForSet().getOperations().delete("小明"); stringRedisTemplate.opsForSet().getOperations().delete( "小海" ); stringRedisTemplate.opsForSet().add( "小明" , "1" ); stringRedisTemplate.opsForSet().add( "小明" , "2" ); stringRedisTemplate.opsForSet().add( "小明" , "5" ); stringRedisTemplate.opsForSet().add( "小海" , "1" ); stringRedisTemplate.opsForSet().add( "小海" , "2" ); stringRedisTemplate.opsForSet().add( "小海" , "3" ); //并集,所有好友 Set<String> allFriends = stringRedisTemplate.opsForSet().union( "小明" , "小海" ); //交集,共同好友 Set<String> sameFriends = stringRedisTemplate.opsForSet().intersect( "小明" , "小海" ); //差集,独有好友 Set<String> privateFriends = stringRedisTemplate.opsForSet().difference( "小明" , "小海" ); |
4.zset
zset又叫sortedset,具有有序的特点,可以用于排行榜:
1 2 3 4 5 6 7 8 9 10 11 12 | /** * 实现排行榜功能 */ public void sort() { stringRedisTemplate.opsForZSet().getOperations().delete( "排行榜" ); stringRedisTemplate.opsForZSet().incrementScore( "排行榜" , "张三" , 10 ); stringRedisTemplate.opsForZSet().incrementScore( "排行榜" , "李四" , 8 ); stringRedisTemplate.opsForZSet().incrementScore( "排行榜" , "王五" , 11 ); stringRedisTemplate.opsForZSet().incrementScore( "排行榜" , "张三" , 10 ); //榜单前三名 Set<ZSetOperations.TypedTuple<String>> sort = stringRedisTemplate.opsForZSet().reverseRangeWithScores( "排行榜" , 0 , 2 ); } |
5.hash
redission分布式锁有对redis hash的运用,实现了锁的可重入;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)