若依框架去掉Redis

这篇文章全是按照我的实战操作来的,本文一是记录一下这个过程,二是帮助更多的人少走弯路。

接下来我们看实战:

第一步毋庸置疑,就是找到配置文件application.yml里面大redis配置部分,直接注释掉

注意这里的data:这是否注释无伤大雅

第二步找到framework下RedisConfig的配置,

全部注释掉,如图,代码如下:

java 复制代码
package com.ruoyi.framework.config;
 
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
/**
 * redis配置
 * 
 * @author ruoyi
 */
@SuppressWarnings("deprecation")
//@Configuration
//@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
//    @Bean
//    @SuppressWarnings(value = { "unchecked", "rawtypes" })
//    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
//    {
//        RedisTemplate<Object, Object> template = new RedisTemplate<>();
//        template.setConnectionFactory(connectionFactory);
//
//        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
//
//        // 使用StringRedisSerializer来序列化和反序列化redis的key值
//        template.setKeySerializer(new StringRedisSerializer());
//        template.setValueSerializer(serializer);
//
//        // Hash的key也采用StringRedisSerializer的序列化方式
//        template.setHashKeySerializer(new StringRedisSerializer());
//        template.setHashValueSerializer(serializer);
//
//        template.afterPropertiesSet();
//        return template;
//    }
//
//    @Bean
//    public DefaultRedisScript<Long> limitScript()
//    {
//        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//        redisScript.setScriptText(limitScriptText());
//        redisScript.setResultType(Long.class);
//        return redisScript;
//    }
//
//    /**
//     * 限流脚本
//     */
//    private String limitScriptText()
//    {
//        return "local key = KEYS[1]\n" +
//                "local count = tonumber(ARGV[1])\n" +
//                "local time = tonumber(ARGV[2])\n" +
//                "local current = redis.call('get', key);\n" +
//                "if current and tonumber(current) > count then\n" +
//                "    return tonumber(current);\n" +
//                "end\n" +
//                "current = redis.call('incr', key)\n" +
//                "if tonumber(current) == 1 then\n" +
//                "    redis.call('expire', key, time)\n" +
//                "end\n" +
//                "return tonumber(current);";
//    }
}

第三步写一个自己的类MyCache,放在

跟RedisCache同目录

代码如下:

java 复制代码
package com.ruoyi.common.core.redis;
 
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.stereotype.Component;
 
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
 
@Component
public class MyCache implements Cache {
 
    // 使用ConcurrentHashMap作为数据的存储
    private Map<String, Object> storage = new ConcurrentHashMap<>();
 
    // getName获取cache的名称,存取数据的时候用来区分是针对哪个cache操作
    @Override
    public String getName() {
        return null;
    }
 
    @Override
    public Object getNativeCache() {
        return null;
    }
 
    public boolean hasKey(String key){
        return storage.containsKey(key);
    }
 
    @Override
    public ValueWrapper get(Object key) {
        String k = key.toString();
        Object value = storage.get(k);
 
        // 注意返回的数据,要和存放时接收到数据保持一致,要将数据反序列化回来。
        return Objects.isNull(value) ? null : new SimpleValueWrapper(value);
    }
 
    @Override
    public <T> T get(Object key, Class<T> type) {
        return null;
    }
 
    @Override
    public <T> T get(Object key, Callable<T> valueLoader) {
        return null;
    }
 
    // put方法,就是执行将数据进行缓存
    @Override
    public void put(Object key, Object value) {
        if (Objects.isNull(value)) {
            return;
        }
        //存值
        storage.put(key.toString(), value);
    }
 
    // evict方法,是用来清除某个缓存项
    @Override
    public void evict(Object key) {
        storage.remove(key.toString());
    }
 
    // 删除集合
    public boolean deleteObject(final Collection collection){
        collection.forEach(o -> {
            storage.remove(o.toString());
        } );
        return true;
    }
 
    // 获取所有的keys
    public Collection<String> keys(final String pattern){
        return storage.keySet();
    }
 
    @Override
    public void clear() {
 
    }
}

第四步修改原来的RedisCache,代码如下:

java 复制代码
package com.ruoyi.common.core.redis;
 
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
 
/**
 * spring redis 工具类
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
//    @Autowired
//    public RedisTemplate redisTemplate;
    @Autowired
    public MyCache myCache;
 
    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        myCache.put(key,value);
//        redisTemplate.opsForValue().set(key, value);
    }
 
    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        myCache.put(key,value);
//        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }
 
    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }
 
    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return true;
//        return redisTemplate.expire(key, timeout, unit);
    }
 
    /**
     * 获取有效时间
     *
     * @param key Redis键
     * @return 有效时间
     */
//    public long getExpire(final String key)
//    {
//        return redisTemplate.getExpire(key);
//    }
 
    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean hasKey(String key)
    {
        return myCache.hasKey(key);
//        return redisTemplate.hasKey(key);
    }
 
    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        Cache.ValueWrapper valueWrapper = myCache.get(key);
        if (valueWrapper == null){
            return null;
        }else {
            return (T) valueWrapper.get();
        }
//        ValueOperations<String, T> operation = redisTemplate.opsForValue();
//        return operation.get(key);
    }
 
    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        myCache.evict(key);
        return true;
//        return redisTemplate.delete(key);
    }
 
    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public boolean deleteObject(final Collection collection)
    {
        return myCache.deleteObject(collection);
//        return redisTemplate.delete(collection) > 0;
    }
 
    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
//    public <T> long setCacheList(final String key, final List<T> dataList)
//    {
//        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
//        return count == null ? 0 : count;
//    }
 
    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
//    public <T> List<T> getCacheList(final String key)
//    {
//        return redisTemplate.opsForList().range(key, 0, -1);
//    }
 
    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
//    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
//    {
//        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
//        Iterator<T> it = dataSet.iterator();
//        while (it.hasNext())
//        {
//            setOperation.add(it.next());
//        }
//        return setOperation;
//    }
 
    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
//    public <T> Set<T> getCacheSet(final String key)
//    {
//        return redisTemplate.opsForSet().members(key);
//    }
 
    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
//    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
//    {
//        if (dataMap != null) {
//            redisTemplate.opsForHash().putAll(key, dataMap);
//        }
//    }
 
//    /**
//     * 获得缓存的Map
//     *
//     * @param key
//     * @return
//     */
//    public <T> Map<String, T> getCacheMap(final String key)
//    {
//        return redisTemplate.opsForHash().entries(key);
//    }
//
//    /**
//     * 往Hash中存入数据
//     *
//     * @param key Redis键
//     * @param hKey Hash键
//     * @param value 值
//     */
//    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
//    {
//        redisTemplate.opsForHash().put(key, hKey, value);
//    }
//
//    /**
//     * 获取Hash中的数据
//     *
//     * @param key Redis键
//     * @param hKey Hash键
//     * @return Hash中的对象
//     */
//    public <T> T getCacheMapValue(final String key, final String hKey)
//    {
//        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
//        return opsForHash.get(key, hKey);
//    }
//
//    /**
//     * 获取多个Hash中的数据
//     *
//     * @param key Redis键
//     * @param hKeys Hash键集合
//     * @return Hash对象集合
//     */
//    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
//    {
//        return redisTemplate.opsForHash().multiGet(key, hKeys);
//    }
//
//    /**
//     * 删除Hash中的某条数据
//     *
//     * @param key Redis键
//     * @param hKey Hash键
//     * @return 是否成功
//     */
//    public boolean deleteCacheMapValue(final String key, final String hKey)
//    {
//        return redisTemplate.opsForHash().delete(key, hKey) > 0;
//    }
 
    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return myCache.keys(pattern);
//        return redisTemplate.keys(pattern);
    }
}

第五步修改ruoyi-common下utils/DictUtils

主要修改的位置:

代码如下:

java 复制代码
package com.it.common.utils;
 
import java.util.Collection;
import java.util.List;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.it.common.constant.CacheConstants;
import com.it.common.core.domain.entity.SysDictData;
import com.it.common.core.redis.RedisCache;
import com.it.common.utils.spring.SpringUtils;
 
/**
 * 字典工具类
 * 
 * @author ruoyi
 */
public class DictUtils
{
    /**
     * 分隔符
     */
    public static final String SEPARATOR = ",";
 
    /**
     * 设置字典缓存
     * 
     * @param key 参数键
     * @param dictDatas 字典数据列表
     */
    public static void setDictCache(String key, List<SysDictData> dictDatas)
    {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas);
    }
 
    /**
     * 获取字典缓存
     * 
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    public static List<SysDictData> getDictCache(String key)
    {
        JSONArray arrayCache = JSONArray.parseArray(JSON.toJSONString(SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key))));
//        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(arrayCache))
        {
            return arrayCache.toList(SysDictData.class);
        }
        return null;
    }
 
    /**
     * 根据字典类型和字典值获取字典标签
     * 
     * @param dictType 字典类型
     * @param dictValue 字典值
     * @return 字典标签
     */
    public static String getDictLabel(String dictType, String dictValue)
    {
        if (StringUtils.isEmpty(dictValue))
        {
            return StringUtils.EMPTY;
        }
        return getDictLabel(dictType, dictValue, SEPARATOR);
    }
 
    /**
     * 根据字典类型和字典标签获取字典值
     * 
     * @param dictType 字典类型
     * @param dictLabel 字典标签
     * @return 字典值
     */
    public static String getDictValue(String dictType, String dictLabel)
    {
        if (StringUtils.isEmpty(dictLabel))
        {
            return StringUtils.EMPTY;
        }
        return getDictValue(dictType, dictLabel, SEPARATOR);
    }
 
    /**
     * 根据字典类型和字典值获取字典标签
     * 
     * @param dictType 字典类型
     * @param dictValue 字典值
     * @param separator 分隔符
     * @return 字典标签
     */
    public static String getDictLabel(String dictType, String dictValue, String separator)
    {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas))
        {
            return StringUtils.EMPTY;
        }
        if (StringUtils.containsAny(separator, dictValue))
        {
            for (SysDictData dict : datas)
            {
                for (String value : dictValue.split(separator))
                {
                    if (value.equals(dict.getDictValue()))
                    {
                        propertyString.append(dict.getDictLabel()).append(separator);
                        break;
                    }
                }
            }
        }
        else
        {
            for (SysDictData dict : datas)
            {
                if (dictValue.equals(dict.getDictValue()))
                {
                    return dict.getDictLabel();
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }
 
    /**
     * 根据字典类型和字典标签获取字典值
     * 
     * @param dictType 字典类型
     * @param dictLabel 字典标签
     * @param separator 分隔符
     * @return 字典值
     */
    public static String getDictValue(String dictType, String dictLabel, String separator)
    {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas))
        {
            return StringUtils.EMPTY;
        }
        if (StringUtils.containsAny(separator, dictLabel))
        {
            for (SysDictData dict : datas)
            {
                for (String label : dictLabel.split(separator))
                {
                    if (label.equals(dict.getDictLabel()))
                    {
                        propertyString.append(dict.getDictValue()).append(separator);
                        break;
                    }
                }
            }
        }
        else
        {
            for (SysDictData dict : datas)
            {
                if (dictLabel.equals(dict.getDictLabel()))
                {
                    return dict.getDictValue();
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }
 
    /**
     * 根据字典类型获取字典所有值
     *
     * @param dictType 字典类型
     * @return 字典值
     */
    public static String getDictValues(String dictType)
    {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas))
        {
            return StringUtils.EMPTY;
        }
        for (SysDictData dict : datas)
        {
            propertyString.append(dict.getDictValue()).append(SEPARATOR);
        }
        return StringUtils.stripEnd(propertyString.toString(), SEPARATOR);
    }
 
    /**
     * 根据字典类型获取字典所有标签
     *
     * @param dictType 字典类型
     * @return 字典值
     */
    public static String getDictLabels(String dictType)
    {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas))
        {
            return StringUtils.EMPTY;
        }
        for (SysDictData dict : datas)
        {
            propertyString.append(dict.getDictLabel()).append(SEPARATOR);
        }
        return StringUtils.stripEnd(propertyString.toString(), SEPARATOR);
    }
 
    /**
     * 删除指定字典缓存
     * 
     * @param key 字典键
     */
    public static void removeDictCache(String key)
    {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
    }
 
    /**
     * 清空字典缓存
     */
    public static void clearDictCache()
    {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }
 
    /**
     * 设置cache key
     * 
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey)
    {
        return CacheConstants.SYS_DICT_KEY + configKey;
    }
}

第六步:

java 复制代码
package com.it.framework.aspectj;
 
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import com.it.common.annotation.RateLimiter;
import com.it.common.enums.LimitType;
import com.it.common.exception.ServiceException;
import com.it.common.utils.StringUtils;
import com.it.common.utils.ip.IpUtils;
 
/**
 * 限流处理
 *
 * @author ruoyi
 */
//@Aspect
//@Component
public class RateLimiterAspect
{
//    private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);
//
//    private RedisTemplate<Object, Object> redisTemplate;
//
//    private RedisScript<Long> limitScript;
//
////    @Autowired
//    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate)
//    {
//        this.redisTemplate = redisTemplate;
//    }
//
////    @Autowired
//    public void setLimitScript(RedisScript<Long> limitScript)
//    {
//        this.limitScript = limitScript;
//    }
//
////    @Before("@annotation(rateLimiter)")
//    public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable
//    {
//        int time = rateLimiter.time();
//        int count = rateLimiter.count();
//
//        String combineKey = getCombineKey(rateLimiter, point);
//        List<Object> keys = Collections.singletonList(combineKey);
//        try
//        {
//            Long number = redisTemplate.execute(limitScript, keys, count, time);
//            if (StringUtils.isNull(number) || number.intValue() > count)
//            {
//                throw new ServiceException("访问过于频繁,请稍候再试");
//            }
//            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), combineKey);
//        }
//        catch (ServiceException e)
//        {
//            throw e;
//        }
//        catch (Exception e)
//        {
//            throw new RuntimeException("服务器限流异常,请稍候再试");
//        }
//    }
//
//    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
//    {
//        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
//        if (rateLimiter.limitType() == LimitType.IP)
//        {
//            stringBuffer.append(IpUtils.getIpAddr()).append("-");
//        }
//        MethodSignature signature = (MethodSignature) point.getSignature();
//        Method method = signature.getMethod();
//        Class<?> targetClass = method.getDeclaringClass();
//        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
//        return stringBuffer.toString();
//    }
}

至此,修改完成,重启项目,搞定收工!

相关推荐
Hellyc4 分钟前
用户查询优惠券之缓存击穿
java·redis·缓存
今天又在摸鱼32 分钟前
Maven
java·maven
老马啸西风34 分钟前
maven 发布到中央仓库常用脚本-02
java·maven
代码的余温35 分钟前
MyBatis集成Logback日志全攻略
java·tomcat·mybatis·logback
一只叫煤球的猫2 小时前
【🤣离谱整活】我写了一篇程序员掉进 Java 异世界的短篇小说
java·后端·程序员
斐波娜娜2 小时前
Maven详解
java·开发语言·maven
Bug退退退1232 小时前
RabbitMQ 高级特性之事务
java·分布式·spring·rabbitmq
程序员秘密基地2 小时前
基于html,css,vue,vscode,idea,,java,springboot,mysql数据库,在线旅游,景点管理系统
java·spring boot·mysql·spring·web3
鼠鼠我捏,要死了捏2 小时前
缓存穿透与击穿多方案对比与实践指南
redis·缓存·实践指南
皮皮林5512 小时前
自从用了CheckStyle插件,代码写的越来越规范了....
java