基于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启动器

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

redis配置:

spring:
  data:
    redis:
      host: localhost
      port: 6379
      jedis:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0

工具类

RedisUtil.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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_58647634/article/details/134935708