redis缓存工具类(Java)

redis常用方法

java 复制代码
package com.guodi.assets.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description:
 * @author: weihao liang
 * @create: 2024-06-15 13:56
 **/
@Service
public class RedisHelper<T> {

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     * @return 缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value) {
        System.out.println(key + "*****" + value.toString());
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value);
        return operation;
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key     缓存的键值
     * @param value   缓存的值
     * @param timeout 超时时间(秒)
     * @return 缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObjectAndtimeout(String key, T value, long timeout) {
        System.out.println(key + "*****" + value.toString());
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value, timeout, TimeUnit.SECONDS);
        return operation;
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList) {
        ListOperations listOperation = redisTemplate.opsForList();
        if (null != dataList) {
            int size = dataList.size();
            for (int i = 0; i < size; i++) {

                listOperation.rightPush(key, dataList.get(i));
            }
        }

        return listOperation;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(String key) {
        List<T> dataList = new ArrayList<T>();
        ListOperations<String, T> listOperation = redisTemplate.opsForList();
        Long size = listOperation.size(key);

        for (int i = 0; i < size; i++) {
            dataList.add((T) listOperation.leftPop(key));
        }

        return dataList;
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
      /*T[] t = (T[]) dataSet.toArray();
        setOperation.add(t);*/


        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }

        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public Set<T> getCacheSet(String key/*,BoundSetOperations<String,T> operation*/) {
        Set<T> dataSet = new HashSet<T>();
        BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);

        Long size = operation.size();
        for (int i = 0; i < size; i++) {
            dataSet.add(operation.pop());
        }
        return dataSet;
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     * @return
     */
    public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) {

        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {

            for (Map.Entry<String, T> entry : dataMap.entrySet()) {

                /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }

        }

        return hashOperations;
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/) {
        Map<String, T> map = redisTemplate.opsForHash().entries(key);
        /*Map<String, T> map = hashOperation.entries(key);*/
        return map;
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     * @return
     */
    public <T> HashOperations<String, Integer, T> setCacheIntegerMap(String key, Map<Integer, T> dataMap) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {

            for (Map.Entry<Integer, T> entry : dataMap.entrySet()) {

                /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }

        }

        return hashOperations;
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<Integer, T> getCacheIntegerMap(String key/*,HashOperations<String,String,T> hashOperation*/) {
        Map<Integer, T> map = redisTemplate.opsForHash().entries(key);
        /*Map<String, T> map = hashOperation.entries(key);*/
        return map;
    }

    /**
     * 删除key
     *
     * @param key
     */
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 删除多个key
     *
     * @param keys
     */
    public void deleteKey(String... keys) {
        Set<String> kSet = Stream.of(keys).map(k -> k).collect(Collectors.toSet());
        redisTemplate.delete(kSet);
    }

    /**
     * 删除Key的集合
     *
     * @param keys
     */
    public void deleteKey(Collection<String> keys) {
        Set<String> kSet = keys.stream().map(k -> k).collect(Collectors.toSet());
        redisTemplate.delete(kSet);
    }

    /**
     * 模糊删除key
     *
     * @param pattern
     */
    public void deleteKeysByPattern(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}

删除缓存

java 复制代码
package com.guodi.assets.map.controller;

import com.guodi.assets.common.utils.RedisHelper;
import com.guodi.core.tool.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description: redis接口用于清理缓存
 * @author: weihao liang
 * @create: 2024-08-13 08:38
 **/
@RestController
@RequestMapping("/mapRedis")
@Api(value = "redis接口用于清理缓存", tags = "redis接口用于清理缓存")
public class MapRedisController {
    @Autowired
    RedisHelper redisHelper;

    @ApiOperation(value = "清除页面统计缓存")
    @GetMapping(value = "/deleteRedis")
    @ResponseBody
    public R refreshRedis() {
        try {
            redisHelper.deleteKeysByPattern("cache_*");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.success("服务器刷新失败!");
        }
        return R.success("服务器内存刷新成功!");
    }

}

如何使用例子

  • 返回参数为list
java 复制代码
List result = new LinkedList<>();

result= JSONArray.parseArray(redisHelper.getCacheObject(rediskey).toString(), JSONObject.class);
  • 返回参数为string
java 复制代码
String analysisRes = null;

String key = "cache" + "_" + operation + "_" + districtCode + "_" + fromYear + "_" + toYear + "_" + item + "_" + subItem;
            if (redisHelper.getCacheObject(key) == null) {
                // 土地SOE接口调用
                String url = getSoeUrl() + "/TendencyStatistics?operation=" + operation + "&districtcode=" + districtCode
                        + "&fromYear=" + fromYear + "&toYear=" + toYear + "&item=" + item + "&subItem="
                        + subItem + "&f=pjson";
                analysisRes = HttpUtil.get(url, -1);
                redisHelper.setCacheObject(key, analysisRes);
            } else {
                analysisRes = redisHelper.getCacheObject(key).toString();
            }
  • 返回参数为对象实体
java 复制代码
List<PriceShow> priceShows = new ArrayList<>();

priceShows = JSON.parseArray(redisHelper.getCacheObject(rediskey).toString(), PriceShow.class);
相关推荐
运行时异常4 小时前
【WMS 仓储系统集成 AI Agent 实战】第 6 讲:RAG 知识库——“输出简单流程“为什么检索不到任何东西
java
小七在进步4 小时前
类和对象(三)
java·开发语言
夜不会漫长4 小时前
C++:类和对象(1)
java·开发语言·c++
czt_java4 小时前
Java文件IO核心知识点总结
java·开发语言
EatFan4 小时前
从单体到模块化:我的 Spring Boot 项目为什么拆成 framework、module、server?
java·spring boot·后端
Java内核笔记4 小时前
Spring Boot 4 可观测性源码剖析:OpenTelemetry 全链路打通日志、指标、追踪
java·后端
Wang's Blog4 小时前
Java框架快速入门: Spring Security+OAuth2之跨域处理
java·开发语言·spring
学渣超4 小时前
从一次早高峰数据库告警说起:你真的理解缓存该如何落地应用吗?
redis·后端·架构
我是大猴子4 小时前
MyBatis‑Plus & MyBatis‑Flex 区别
java·服务器·数据库
Bs_MoneyMagnet4 小时前
基于springboot+vue的在线音乐管理系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring