這篇文章全是按照我的實戰操作來的,本文一是記錄一下這個過程,二是幫助更多的人少走彎路。
接下來我們看實戰:
第一步毋庸置疑,就是找到配置文件application.yml里面大redis配置部分,直接注釋掉
注意這里的data:這是否注釋無傷大雅
第二步找到framework下RedisConfig的配置,
全部注釋掉,如圖,代碼如下:
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同目錄
代碼如下:
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操作@Overridepublic String getName() {return null;}@Overridepublic Object getNativeCache() {return null;}public boolean hasKey(String key){return storage.containsKey(key);}@Overridepublic ValueWrapper get(Object key) {String k = key.toString();Object value = storage.get(k);// 注意返回的數據,要和存放時接收到數據保持一致,要將數據反序列化回來。return Objects.isNull(value) ? null : new SimpleValueWrapper(value);}@Overridepublic <T> T get(Object key, Class<T> type) {return null;}@Overridepublic <T> T get(Object key, Callable<T> valueLoader) {return null;}// put方法,就是執行將數據進行緩存@Overridepublic void put(Object key, Object value) {if (Objects.isNull(value)) {return;}//存值storage.put(key.toString(), value);}// evict方法,是用來清除某個緩存項@Overridepublic void evict(Object key) {storage.remove(key.toString());}// 刪除集合public boolean deleteObject(final Collection collection){collection.forEach(o -> {storage.remove(o.toString());} );return true;}// 獲取所有的keyspublic Collection<String> keys(final String pattern){return storage.keySet();}@Overridepublic void clear() {}
}
第四步修改原來的RedisCache,代碼如下:
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;@Autowiredpublic 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
主要修改的位置:
代碼如下:
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;}
}
第六步:
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();
// }
}
至此,修改完成,重啟項目,搞定收工!