Redis 基本数据类型及其适用场景与案例

devtools/2025/2/25 6:48:58/

Redis 基本数据类型及其适用场景与案例

Redis 提供了多种数据类型,每种数据类型都有其特定的使用场景。以下是对每种数据类型的详细解释、适用场景以及使用 Spring Boot 实现的案例。

1. String(字符串)
  • 特点:最基本的数据类型,可以存储字符串、整数或浮点数。
  • 适用场景:缓存简单的键值对数据,如用户会话、计数器等。
  • 案例:缓存用户会话信息,设置过期时间为 30 分钟。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;@Service
public class UserSessionService {@Autowiredprivate StringRedisTemplate redisTemplate;public void cacheUserSession(String userId, String sessionData) {redisTemplate.opsForValue().set("user:session:" + userId, sessionData, 30, TimeUnit.MINUTES);}public String getUserSession(String userId) {return redisTemplate.opsForValue().get("user:session:" + userId);}
}
2. Hash(哈希)
  • 特点:类似于 Java 中的 Map,存储键值对集合。
  • 适用场景:缓存对象数据,如用户信息、商品信息等。
  • 案例:缓存用户信息,设置过期时间为 1 小时。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;@Service
public class UserInfoService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;public void cacheUserInfo(String userId, Map<String, String> userInfo) {HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();hashOps.putAll("user:info:" + userId, userInfo);redisTemplate.expire("user:info:" + userId, 1, TimeUnit.HOURS);}public Map<String, String> getUserInfo(String userId) {HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();return hashOps.entries("user:info:" + userId);}
}
3. List(列表)
  • 特点:有序的字符串列表,可以在列表的两端进行插入和删除操作。
  • 适用场景:消息队列、最新消息列表等。
  • 案例:实现一个简单的消息队列,设置过期时间为 1 天。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;@Service
public class MessageQueueService {@Autowiredprivate RedisTemplate<String, String> redisTemplate;public void pushMessage(String queueName, String message) {ListOperations<String, String> listOps = redisTemplate.opsForList();listOps.rightPush(queueName, message);redisTemplate.expire(queueName, 1, TimeUnit.DAYS);}public String popMessage(String queueName) {ListOperations<String, String> listOps = redisTemplate.opsForList();return listOps.leftPop(queueName);}
}
4. Set(集合)
  • 特点:无序且不重复的字符串集合。
  • 适用场景:去重数据存储、标签系统等。
  • 案例:存储用户的标签信息,设置过期时间为 2 小时。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.concurrent.TimeUnit;@Service
public class UserTagService {@Autowiredprivate RedisTemplate<String, String> redisTemplate;public void addUserTags(String userId, Set<String> tags) {SetOperations<String, String> setOps = redisTemplate.opsForSet();setOps.add("user:tags:" + userId, tags.toArray(new String[0]));redisTemplate.expire("user:tags:" + userId, 2, TimeUnit.HOURS);}public Set<String> getUserTags(String userId) {SetOperations<String, String> setOps = redisTemplate.opsForSet();return setOps.members("user:tags:" + userId);}
}
5. Sorted Set(有序集合)
  • 特点:与 Set 类似,但每个元素都会关联一个分数,用于排序。
  • 适用场景:排行榜、优先级队列等。
  • 案例:实现一个用户积分排行榜,设置过期时间为 1 天。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.concurrent.TimeUnit;@Service
public class LeaderboardService {@Autowiredprivate RedisTemplate<String, String> redisTemplate;public void addUserScore(String userId, double score) {ZSetOperations<String, String> zSetOps = redisTemplate.opsForZSet();zSetOps.add("leaderboard", userId, score);redisTemplate.expire("leaderboard", 1, TimeUnit.DAYS);}public Set<ZSetOperations.TypedTuple<String>> getTopUsers(int topN) {ZSetOperations<String, String> zSetOps = redisTemplate.opsForZSet();return zSetOps.reverseRangeWithScores("leaderboard", 0, topN - 1);}
}

总结

通过以上案例,你可以看到 Redis 的各种数据类型在不同场景下的应用。结合 Spring Boot 和 Redis,可以轻松实现缓存、消息队列、排行榜等功能,并通过设置合适的过期时间来管理数据的生命周期。


http://www.ppmy.cn/devtools/161516.html

相关文章

国产超强开源大语言模型 DeepSeek-R1-70B 一键部署教程

DeepSeek-R1-Distill-Llama-70B 是深度求索 (DeepSeek) 公司于 2025 年推出的开源大语言模型&#xff0c;参数规模高达 700 亿。它是基于 Llama3.3-70B-Instruct 进行训练的&#xff0c;采用强化学习和蒸馏技术提升推理表现&#xff0c;不仅继承了 Llama 系列模型的优势&#x…

【1】VS Code 新建上位机项目---C#基础语法

VS Code 新建上位机项目---C#基础语法 1 基本概念1.1 准备工具1.2 新建项目2 C#编程基础2.1 命名空间和类2.2 数据类型2.3 控制台输入输出2.3.1 输入输出: write 与 read2.3.2 格式化 : string.Foramt() 与 $2.3.3 赋值与运算2.4 类型转换2.4.1 数值类型之间的转换:(int)2.4…

MATLAB实现四阶龙格库塔法求解常微分方程组

MATLAB实现四阶龙格库塔法求解常微分方程组 MATLAB实现四阶龙格库塔法求解常微分方程组/f.m , 107 MATLAB实现四阶龙格库塔法求解常微分方程组/RungeKutta.m , 844 MATLAB实现四阶龙格库塔法求解常微分方程组/四阶龙格库塔法求解常微分方程组.pdf , 93258

自注意力机制和CNN的区别

CNN&#xff1a;一种只能在固定感受野范围内进行关注的自注意力机制。​CNN是自注意力的简化版本。自注意力&#xff1a;具有可学习感受野的CNN。自注意力是CNN的复杂形态&#xff0c;是更灵活的CNN&#xff0c;经过某些设计就可以变为CNN。 越灵活、越大的模型&#xff0c;需要…

鸿蒙5.0实战案例:基于原生能力的深色模式适配

往期推文全新看点&#xff08;文中附带全新鸿蒙5.0全栈学习笔录&#xff09; ✏️ 鸿蒙&#xff08;HarmonyOS&#xff09;北向开发知识点记录~ ✏️ 鸿蒙&#xff08;OpenHarmony&#xff09;南向开发保姆级知识点汇总~ ✏️ 鸿蒙应用开发与鸿蒙系统开发哪个更有前景&#…

HTML之JavaScript DOM编程获取元素的方式

HTML之JavaScript DOM编程获取元素的方式 1.获得document DOM树window.document(是window的属性)2.从document中获取要操作的元素1.直接获取var aaa document.getElementById("username") // 根据元素的id值获取页面上的唯一一个元素,有同名的则返回找到的第一个var…

java23种设计模式-原型模式

原型模式&#xff08;Prototype Pattern&#xff09;学习笔记 &#x1f31f; 定义 原型模式属于创建型设计模式&#xff0c;通过复制现有对象&#xff08;原型&#xff09;来创建新对象&#xff0c;避免重复进行初始化操作。该模式的核心是实现对象的克隆能力。 &#x1f3af…

Java基础进阶提升

(一)Java基础 面向对象java语法常用类&#xff0c;api数据类型方法、对象、引用运算符、操作符关键字、关键词 (二)java进阶 异常、异常分类与处理线程同步、守护线程多线程、IO流接口、多继承jdk、jre、jvm反射、泛型类继承、方法覆盖 (三)数据库 Mysql数据库Oracle数据库…