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

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

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

1. String(字符串)
  • 特点:最基本的数据类型,可以存储字符串、整数或浮点数。
  • 适用场景:缓存简单的键值对数据,如用户会话、计数器等。
  • 案例:缓存用户会话信息,设置过期时间为 30 分钟。
java 复制代码
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 {

    @Autowired
    private 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 小时。
java 复制代码
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 {

    @Autowired
    private 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 天。
java 复制代码
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 {

    @Autowired
    private 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 小时。
java 复制代码
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 {

    @Autowired
    private 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 天。
java 复制代码
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 {

    @Autowired
    private 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,可以轻松实现缓存、消息队列、排行榜等功能,并通过设置合适的过期时间来管理数据的生命周期。

相关推荐
JavaPub-rodert12 分钟前
Redis 和 MySQL 如何保证数据一致性?从业务方案到底层原理完整讲解
数据库·redis·mysql
重生之我是Java开发战士20 分钟前
【Spring Cloud】认识微服务与工程搭建
spring·spring cloud·微服务
霸道流氓气质24 分钟前
Spring AI 多模态开发指南:图片理解与语音合成
java·人工智能·spring
后台模板学习34 分钟前
用 IM 即时聊天项目一次讲清消息去重算法的踩坑与解决方案
java·数据库·spring
霸道流氓气质2 小时前
Spring AI 技术细节:VectorStore 多库统一抽象
java·人工智能·spring
逃逸线LOF2 小时前
Spring的AOP简介
java·后端·spring
Zzzzmo_3 小时前
Spring MVC
java·spring·mvc·cookie/session
cfm_29143 小时前
Spring核心设计模式
java·spring·设计模式
Java小白笔记3 小时前
Java 实现阿里云 OSS 文件上传链路:普通上传、秒传、分片与断点续传
java·开发语言·数据库·spring·阿里云
cui_hao_nan4 小时前
Spring AOP 自调用、代理与 private 方法引发的诡异 NPE
java·后端·spring·ai开发