基于java的Redis工具类可缓存Object,list,set,map!!!

目录


简介:

添加redis启动器,配置redis相关配置,使用工具类缓存数据
封装的方法有:缓存Object,list,set,map类型数据的方法、获取指定key的value、判断指定key是否有、设置key的有效期
用的类介绍:

TypeReference:

这个类是 Jackson 库中的一个工具类,它允许你保留 Java 类型的泛型信息。由于 Java 的类型擦除机制,通常情况下在运行时无法获取到泛型的实际类型参数。但是通过使用
TypeReference,你可以创建一个包装类来保存泛型类型,并将其传递给 Jackson 的方法(如 readValue() 和 writeValueAsString()),以便正确地处理泛型。

ObjectMapper:

可以序列化:将 Java 对象转换为 JSON 字符串

也可以反序列化:将 JSON 字符串解析为 Java 对象

StringRedisTemplate:操作 Redis 数据库中的字符串值,可以自动处理 Java 对象与 Redis 存储的字符串之间的转换,有很多的扩展方法。

springboot redis启动器

xml 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

redis配置:

yml 复制代码
spring:
  data:
    redis:
      host: localhost
      port: 6379
      jedis:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0

工具类

RedisUtil.java

java 复制代码
package com.ekgc.qy.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Monk
 * @program: qyBootMaven
 * @description: redis缓存工具类
 * @create: 2023-12-11 16:56
 */
@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static ObjectMapper objectMapper = new ObjectMapper();

    // 检查给定的键是否存在于缓存中
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    // 设置给定键的生存时间(以秒为单位)
    public void setExpireTime(String key, long seconds) {
        stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    // 缓存一个对象
    // 尖括号<T>声明一个泛型
    public <T> void setObject(String key, T value) {
        try {
            String jsonValue = objectMapper.writeValueAsString(value);
            stringRedisTemplate.opsForValue().set(key, jsonValue);
        } catch (Exception e) {
            throw new RuntimeException("Failed to cache object", e);
        }
    }

    // 从缓存中获取一个对象
    public <T> T getObject(String key, Class<T> clazz) {
        String jsonValue = stringRedisTemplate.opsForValue().get(key);
        if (jsonValue == null) {
            return null;
        }

        try {
            return objectMapper.readValue(jsonValue, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse cached object", e);
        }
    }

    // 缓存一个列表
    public <T> void setList(String key, List<T> list) {
        try {
            String jsonValue = objectMapper.writeValueAsString(list);
            stringRedisTemplate.opsForValue().set(key, jsonValue);
        } catch (Exception e) {
            throw new RuntimeException("Failed to cache list", e);
        }
    }

    // 从缓存中获取一个列表
    public <T> List<T> getList(String key, Class<T> elementType) {
        String jsonValue = stringRedisTemplate.opsForValue().get(key);
        if (jsonValue == null) {
            return null;
        }

        try {
            TypeReference<List<T>> typeRef = new TypeReference<>() {};
            return objectMapper.readValue(jsonValue, typeRef);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse cached list", e);
        }
    }

    // 缓存一个集合
    public <T> void setSet(String key, Set<T> set) {
        try {
            String jsonValue = objectMapper.writeValueAsString(set);
            stringRedisTemplate.opsForValue().set(key, jsonValue);
        } catch (Exception e) {
            throw new RuntimeException("Failed to cache set", e);
        }
    }

    // 从缓存中获取一个集合
    public <T> Set<T> getSet(String key, Class<T> elementType) {
        String jsonValue = stringRedisTemplate.opsForValue().get(key);
        if (jsonValue == null) {
            return null;
        }

        try {
            TypeReference<Set<T>> typeRef = new TypeReference<>() {};
            return objectMapper.readValue(jsonValue, typeRef);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse cached set", e);
        }
    }

    // 缓存一个映射
    public <K, V> void setMap(String key, Map<K, V> map) {
        try {
            String jsonValue = objectMapper.writeValueAsString(map);
            stringRedisTemplate.opsForValue().set(key, jsonValue);
        } catch (Exception e) {
            throw new RuntimeException("Failed to cache map", e);
        }
    }

    // 从缓存中获取一个映射
    public <K, V> Map<K, V> getMap(String key, Class<K> keyType, Class<V> valueType) {
        String jsonValue = stringRedisTemplate.opsForValue().get(key);
        if (jsonValue == null) {
            return null;
        }

        try {
            TypeReference<Map<K, V>> typeRef = new TypeReference<>() {};
            return objectMapper.readValue(jsonValue, typeRef);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse cached map", e);
        }
    }
}
相关推荐
panxianren4 小时前
Bun 1.4 的 bun test --parallel 将 4 秒的测试套件缩短到约 1 秒
java·javascript
sunshine22 girl6 小时前
Java学习七 Java 项目实战2-注册业务
java·学习
省钱兄--zs6 小时前
北京24小时自助健身房系统软件开发实战:从架构设计到部署指南
java·数据仓库·spring boot·小程序·需求分析
youdexiang7 小时前
Android录音软件时间关键词检索功能分析
java·人工智能
sunshine22 girl7 小时前
Java学习七 Java 项目实战1-项目创建和主页面搭建
java·开发语言·学习
code2cat7 小时前
Java进阶篇之AtomicStampedReference:引用回到原值,版本戳仍能记住变化
java·cas·并发编程·aba
泡茶喝茶写代码9 小时前
A股量化数据工程:从 REST 接口到策略信号(第 8 篇):成长能力因子:营收与利润增速
java·python·股票数据api·股票数据api接口·股票量化数据api·股票量化数据接口·股票数据api数据
\光辉岁月/10 小时前
7.javase-面向对象
java·开发语言
weixin_5310946910 小时前
heap_4内存管理
java·开发语言·算法
程序员南飞10 小时前
win系统安装minio
java·数据结构·算法