【Java】Redis存储和获取泛型

需求:在实际开发过程中,Redis需要存储不同类型的值,创建一个泛型工具类,用于包装 RedisTemplate,使其支持泛型进行存储和获取,下面就写一个栗子进行演示。

RedisUtils:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public <T> void saveList(String key, List<T> list) {
        //redisTemplate.opsForList().leftPush(key, list);
        redisTemplate.opsForValue().set(key, list);
    }

    public <T> List<T> getList(String key) {
        //return (List<T>) redisTemplate.opsForList().range(key, 0, -1);
        return (List<T>) redisTemplate.opsForValue().get(key);
    }
}

假设有一个 UserService 的服务实现类需要redis进行存储和获取数据:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisService redisService;

    @Override
    public void saveUsers(String key, List<User> userList) {
        redisService.saveList(key, userList);
    }

    @Override
    public List<User> getUsers(String key) {
        return redisService.getList(key);
    }
}

这样就很方便的存储多种类型的数据了。

相关推荐
大模型丫丫21 分钟前
Loop Engineering:从强化学习视角看 Agent 循环的本质
java·人工智能·学习
数电发票API24 分钟前
税局接口,需要的来~~
java
骇客野人36 分钟前
IntelliJ IDEA 使用技巧
java·ide·intellij-idea
大尚来也42 分钟前
用 Python 自动整理文件、重命名、分类电脑文件夹
开发语言·python
CVer儿44 分钟前
c++二级指针
开发语言·c++
Jul1en_1 小时前
【Java 脚手架】封装通用工具类-1
java·spring boot·分布式·spring·spring cloud
mlidongfeng1 小时前
[AI][C++26] SIMD 编程模型思考
开发语言·c++·人工智能
j7~1 小时前
【Linux】二十七.线程篇四《Linux多线程编程:线程互斥(互斥量的底层到封装)、线程安全和冲入、死锁》---详解
linux·开发语言·c++·线程安全·死锁·线程互斥·重入
关于不上作者榜就原神启动那件事2 小时前
从 MDC 到 Agent:我手搓的文档路由协议,在 Spring AI Alibaba 里找到了正式实现
java·人工智能·spring·ai·agent
刘名喜2 小时前
第09篇-协程基础-Kotlin异步编程
开发语言·kotlin·springboot