commit:单体工程目录

This commit is contained in:
Jerry
2021-09-28 16:29:18 +08:00
parent a6ae0d1a79
commit 50807a7a7e
550 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>common</artifactId>
<groupId>com.orange.demo</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common-redis</artifactId>
<version>1.0.0</version>
<name>common-redis</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.orange.demo</groupId>
<artifactId>common-core</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>${redisson.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,412 @@
package com.orange.demo.common.redis.cache;
import com.alibaba.fastjson.JSON;
import com.orange.demo.common.core.cache.DictionaryCache;
import com.orange.demo.common.core.constant.ApplicationConstant;
import com.orange.demo.common.core.exception.RedisCacheAccessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 字典数据Redis缓存对象。
*
* @param <K> 字典表主键类型。
* @param <V> 字典表对象类型。
* @author Jerry
* @date 2020-09-24
*/
@Slf4j
public class RedisDictionaryCache<K, V> implements DictionaryCache<K, V> {
/**
* redisson客户端。
*/
protected final RedissonClient redissonClient;
/**
* 数据存储对象。
*/
protected final RMap<K, String> dataMap;
/**
* 字典值对象类型。
*/
protected final Class<V> valueClazz;
/**
* 由于大部分场景是读取操作,所以使用读写锁提高并发的伸缩性。
*/
protected final ReadWriteLock lock;
/**
* 获取字典主键数据的函数对象。
*/
protected final Function<V, K> idGetter;
/**
* 超时时长。单位毫秒。
*/
protected static final long TIMEOUT = 2000L;
/**
* 当前对象的构造器函数。
*
* @param redissonClient Redisson的客户端对象。
* @param dictionaryName 字典表的名称。等同于redis hash对象的key。
* @param valueClazz 值对象的Class对象。
* @param idGetter 获取当前类主键字段值的函数对象。
* @param <K> 字典主键类型。
* @param <V> 字典对象类型
* @return 实例化后的字典内存缓存对象。
*/
public static <K, V> RedisDictionaryCache<K, V> create(
RedissonClient redissonClient,
String dictionaryName,
Class<V> valueClazz,
Function<V, K> idGetter) {
if (idGetter == null) {
throw new IllegalArgumentException("IdGetter can't be NULL.");
}
return new RedisDictionaryCache<>(redissonClient, dictionaryName, valueClazz, idGetter);
}
/**
* 构造函数。
*
* @param redissonClient Redisson的客户端对象。
* @param dictionaryName 字典表的名称。等同于redis hash对象的key。确保全局唯一。
* @param valueClazz 值对象的Class对象。
* @param idGetter 获取当前类主键字段值的函数对象。
*/
public RedisDictionaryCache(
RedissonClient redissonClient,
String dictionaryName,
Class<V> valueClazz,
Function<V, K> idGetter) {
this.redissonClient = redissonClient;
this.dataMap = redissonClient.getMap(dictionaryName + ApplicationConstant.DICT_CACHE_NAME_SUFFIX);
this.lock = new ReentrantReadWriteLock();
this.valueClazz = valueClazz;
this.idGetter = idGetter;
}
/**
* 按照数据插入的顺序返回全部字典对象的列表。
*
* @return 全部字段数据列表。
*/
@Override
public List<V> getAll() {
Collection<String> dataList;
String exceptionMessage;
try {
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataList = dataMap.readAllValues();
} finally {
// 如果上面的操作时间超过redisson.lockWatchdogTimeout的时长
// redis会将与该锁关联的键删除此后调用unlock的时候就会抛出运行时异常。
lock.readLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::getAll] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
if (CollectionUtils.isEmpty(dataList)) {
return new LinkedList<>();
}
return dataList.stream()
.map(data -> JSON.parseObject(data, valueClazz))
.collect(Collectors.toCollection(LinkedList::new));
}
/**
* 获取缓存中与键列表对应的对象列表。
*
* @param keys 主键集合。
* @return 对象列表。
*/
@Override
public List<V> getInList(Set<K> keys) {
if (CollectionUtils.isEmpty(keys)) {
return new LinkedList<>();
}
Collection<String> dataList;
String exceptionMessage;
try {
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataList = dataMap.getAll(keys).values();
} finally {
lock.readLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
if (dataList == null) {
return new LinkedList<>();
}
return dataList.stream()
.map(data -> JSON.parseObject(data, valueClazz))
.collect(Collectors.toCollection(LinkedList::new));
}
/**
* 从缓存中获取指定的数据。
*
* @param id 数据的key。
* @return 获取到的数据如果没有返回null。
*/
@Override
public V get(K id) {
if (id == null) {
return null;
}
String data;
String exceptionMessage;
try {
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
data = dataMap.get(id);
} finally {
lock.readLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::get] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
if (data == null) {
return null;
}
return JSON.parseObject(data, valueClazz);
}
/**
* 获取缓存中数据条目的数量。
*
* @return 返回缓存的数据数量。
*/
@Override
public int getCount() {
return dataMap.size();
}
/**
* 将参数List中的数据保存到缓存中同时保证getAll返回的数据列表与参数列表中数据项的顺序保持一致。
*
* @param dataList 待缓存的数据列表。
*/
@Override
public void putAll(List<V> dataList) {
if (CollectionUtils.isEmpty(dataList)) {
return;
}
Map<K, String> map = dataList.stream()
.collect(Collectors.toMap(idGetter, JSON::toJSONString));
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataMap.putAll(map, 1000);
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::putAll] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 将数据存入缓存。
*
* @param id 通常为字典数据的主键。
* @param data 字典数据对象。
*/
@Override
public void put(K id, V data) {
if (id == null || data == null) {
return;
}
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataMap.fastPut(id, JSON.toJSONString(data));
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::put] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 重新加载先清空原有数据在执行putAll的操作。
*
* @param dataList 待缓存的数据列表。
* @param force true则强制刷新如果false当缓存中存在数据时不刷新。
*/
@Override
public void reload(List<V> dataList, boolean force) {
Map<K, String> map = null;
if (CollectionUtils.isNotEmpty(dataList)) {
map = dataList.stream().collect(Collectors.toMap(idGetter, JSON::toJSONString));
}
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
// 如果不强制刷新,需要先判断缓存中是否存在数据。
if (!force && this.getCount() > 0) {
return;
}
dataMap.clear();
if (map != null) {
dataMap.putAll(map, 1000);
}
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::reload] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 删除缓存中指定的键。
*
* @param id 待删除数据的主键。
* @return 返回被删除的对象如果主键不存在返回null。
*/
@Override
public V invalidate(K id) {
if (id == null) {
return null;
}
String data;
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
data = dataMap.remove(id);
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::invalidate] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
if (data == null) {
return null;
}
return JSON.parseObject(data, valueClazz);
}
/**
* 删除缓存中,参数列表中包含的键。
*
* @param keys 待删除数据的主键集合。
*/
@SuppressWarnings("unchecked")
@Override
public void invalidateSet(Set<K> keys) {
if (CollectionUtils.isEmpty(keys)) {
return;
}
Object[] keyArray = keys.toArray(new Object[]{});
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataMap.fastRemove((K[]) keyArray);
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::invalidateSet] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 清空缓存。
*/
@Override
public void invalidateAll() {
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataMap.clear();
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::invalidateAll] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
}

View File

@@ -0,0 +1,354 @@
package com.orange.demo.common.redis.cache;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import com.orange.demo.common.core.constant.ApplicationConstant;
import com.orange.demo.common.core.exception.RedisCacheAccessException;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RListMultimap;
import org.redisson.api.RedissonClient;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 树形字典数据Redis缓存对象。
*
* @param <K> 字典表主键类型。
* @param <V> 字典表对象类型。
* @author Jerry
* @date 2020-09-24
*/
@Slf4j
public class RedisTreeDictionaryCache<K, V> extends RedisDictionaryCache<K, V> {
/**
* 树形数据存储对象。
*/
private final RListMultimap<K, String> allTreeMap;
/**
* 获取字典父主键数据的函数对象。
*/
protected final Function<V, K> parentIdGetter;
/**
* 当前对象的构造器函数。
*
* @param redissonClient Redisson的客户端对象。
* @param dictionaryName 字典表的名称。等同于redis hash对象的key。
* @param valueClazz 值对象的Class对象。
* @param idGetter 获取当前类主键字段值的函数对象。
* @param parentIdGetter 获取当前类父主键字段值的函数对象。
* @param <K> 字典主键类型。
* @param <V> 字典对象类型
* @return 实例化后的树形字典内存缓存对象。
*/
public static <K, V> RedisTreeDictionaryCache<K, V> create(
RedissonClient redissonClient,
String dictionaryName,
Class<V> valueClazz,
Function<V, K> idGetter,
Function<V, K> parentIdGetter) {
if (idGetter == null) {
throw new IllegalArgumentException("IdGetter can't be NULL.");
}
if (parentIdGetter == null) {
throw new IllegalArgumentException("ParentIdGetter can't be NULL.");
}
return new RedisTreeDictionaryCache<>(
redissonClient, dictionaryName, valueClazz, idGetter, parentIdGetter);
}
/**
* 构造函数。
*
* @param redissonClient Redisson的客户端对象。
* @param dictionaryName 字典表的名称。等同于redis hash对象的key。
* @param valueClazz 值对象的Class对象。
* @param idGetter 获取当前类主键字段值的函数对象。
* @param parentIdGetter 获取当前类父主键字段值的函数对象。
*/
public RedisTreeDictionaryCache(
RedissonClient redissonClient,
String dictionaryName,
Class<V> valueClazz,
Function<V, K> idGetter,
Function<V, K> parentIdGetter) {
super(redissonClient, dictionaryName, valueClazz, idGetter);
this.allTreeMap = redissonClient.getListMultimap(
dictionaryName + ApplicationConstant.TREE_DICT_CACHE_NAME_SUFFIX);
this.parentIdGetter = parentIdGetter;
}
/**
* 获取该父主键的子数据列表。
*
* @param parentId 父主键Id。如果parentId为null则返回所有一级节点数据。
* @return 子数据列表。
*/
public List<V> getListByParentId(K parentId) {
List<String> dataList;
String exceptionMessage;
try {
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataList = allTreeMap.get(parentId);
} finally {
lock.readLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisTreeDictionaryCache::getListByParentId] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
if (CollectionUtils.isEmpty(dataList)) {
return new LinkedList<>();
}
List<V> resultList = new LinkedList<>();
dataList.forEach(data -> resultList.add(JSON.parseObject(data, valueClazz)));
return resultList;
}
/**
* 将参数List中的数据保存到缓存中同时保证getAll返回的数据列表与参数列表中数据项的顺序保持一致。
*
* @param dataList 待缓存的数据列表。
*/
@Override
public void putAll(List<V> dataList) {
if (CollectionUtils.isEmpty(dataList)) {
return;
}
// 锁外执行数据结构组装,降低锁的粒度,提高并发性。
Map<K, String> map = dataList.stream()
.collect(Collectors.toMap(idGetter, JSON::toJSONString));
Multimap<K, String> treeMap = LinkedListMultimap.create();
for (V data : dataList) {
treeMap.put(parentIdGetter.apply(data), JSON.toJSONString(data));
}
Set<Map.Entry<K, Collection<String>>> entries = treeMap.asMap().entrySet();
String exceptionMessage;
try {
if (this.lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataMap.putAll(map, 1000);
for (Map.Entry<K, Collection<String>> entry : entries) {
allTreeMap.removeAll(entry.getKey());
allTreeMap.putAll(entry.getKey(), entry.getValue());
}
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisTreeDictionaryCache::putAll] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 将数据存入缓存。
*
* @param id 通常为字典数据的主键。
* @param data 字典数据对象。
*/
@Override
public void put(K id, V data) {
if (id == null || data == null) {
return;
}
String stringData = JSON.toJSONString(data);
K parentId = parentIdGetter.apply(data);
String exceptionMessage;
try {
if (this.lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
String oldData = dataMap.put(id, stringData);
if (oldData != null) {
allTreeMap.remove(parentId, oldData);
}
allTreeMap.put(parentId, stringData);
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisTreeDictionaryCache::put] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 行为等同于接口中的描述。这里之所以重写是因为不确定redisson的读写锁
* 是否为可重入锁。
*
* @param dataList 待缓存的数据列表。
* @param force true则强制刷新如果false当缓存中存在数据时不刷新。
*/
@Override
public void reload(List<V> dataList, boolean force) {
// 锁外执行数据结构组装,降低锁的粒度,提高并发性。
Map<K, String> map = null;
Set<Map.Entry<K, Collection<String>>> entries = null;
if (CollectionUtils.isNotEmpty(dataList)) {
map = dataList.stream().collect(Collectors.toMap(idGetter, JSON::toJSONString));
Multimap<K, String> treeMap = LinkedListMultimap.create();
for (V data : dataList) {
treeMap.put(parentIdGetter.apply(data), JSON.toJSONString(data));
}
entries = treeMap.asMap().entrySet();
}
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
// 如果不强制刷新,需要先判断缓存中是否存在数据。
if (!force && this.getCount() > 0) {
return;
}
dataMap.clear();
allTreeMap.clear();
if (map != null) {
dataMap.putAll(map, 1000);
for (Map.Entry<K, Collection<String>> entry : entries) {
allTreeMap.removeAll(entry.getKey());
allTreeMap.putAll(entry.getKey(), entry.getValue());
}
}
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisDictionaryCache::reload] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 删除缓存中指定的键。
*
* @param id 待删除数据的主键。
* @return 返回被删除的对象如果主键不存在返回null。
*/
@Override
public V invalidate(K id) {
if (id == null) {
return null;
}
V data = null;
String exceptionMessage;
try {
if (this.lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
String stringData = dataMap.remove(id);
if (stringData != null) {
data = JSON.parseObject(stringData, valueClazz);
K parentId = parentIdGetter.apply(data);
allTreeMap.remove(parentId, stringData);
}
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisTreeDictionaryCache::invalidate] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
return data;
}
/**
* 删除缓存中,参数列表中包含的键。
*
* @param keys 待删除数据的主键集合。
*/
@Override
public void invalidateSet(Set<K> keys) {
if (CollectionUtils.isEmpty(keys)) {
return;
}
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
keys.forEach(id -> {
if (id != null) {
String stringData = dataMap.remove(id);
if (stringData != null) {
K parentId = parentIdGetter.apply(JSON.parseObject(stringData, valueClazz));
allTreeMap.remove(parentId, stringData);
}
}
});
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisTreeDictionaryCache::invalidateSet] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
/**
* 清空缓存。
*/
@Override
public void invalidateAll() {
String exceptionMessage;
try {
if (lock.writeLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
try {
dataMap.clear();
allTreeMap.clear();
} finally {
lock.writeLock().unlock();
}
} else {
throw new TimeoutException();
}
} catch (Exception e) {
exceptionMessage = String.format(
"LOCK Operation of [RedisTreeDictionaryCache::invalidateAll] encountered EXCEPTION [%s] for DICT [%s].",
e.getClass().getSimpleName(), valueClazz.getSimpleName());
log.warn(exceptionMessage);
throw new RedisCacheAccessException(exceptionMessage, e);
}
}
}

View File

@@ -0,0 +1,67 @@
package com.orange.demo.common.redis.cache;
import com.google.common.collect.Maps;
import org.redisson.api.RedissonClient;
import org.redisson.spring.cache.CacheConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
/**
* 使用Redisson作为Redis的分布式缓存库。
*
* @author Jerry
* @date 2020-09-24
*/
@Configuration
@EnableCaching
public class RedissonCacheConfig {
private static final int DEFAULT_TTL = 3600000;
/**
* 定义cache名称、超时时长(毫秒)。
*/
public enum CacheEnum {
/**
* session下上传文件名的缓存(时间是24小时)。
*/
UPLOAD_FILENAME_CACHE(86400000),
/**
* 缺省全局缓存(时间是24小时)。
*/
GLOBAL_CACHE(86400000);
/**
* 缓存的时长(单位:毫秒)
*/
private int ttl = DEFAULT_TTL;
CacheEnum() {
}
CacheEnum(int ttl) {
this.ttl = ttl;
}
public int getTtl() {
return ttl;
}
}
/**
* 初始化缓存配置。
*/
@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = Maps.newHashMap();
for (CacheEnum c : CacheEnum.values()) {
config.put(c.name(), new CacheConfig(c.getTtl(), 0));
}
return new RedissonSpringCacheManager(redissonClient, config);
}
}

View File

@@ -0,0 +1,74 @@
package com.orange.demo.common.redis.cache;
import com.orange.demo.common.core.object.TokenData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
/**
* Session数据缓存辅助类。
*
* @author Jerry
* @date 2020-09-24
*/
@SuppressWarnings("unchecked")
@Component
public class SessionCacheHelper {
@Autowired
private CacheManager cacheManager;
/**
* 缓存当前session内上传过的文件名。
*
* @param filename 通常是本地存储的文件名,而不是上传时的原始文件名。
*/
public void putSessionUploadFile(String filename) {
if (filename != null) {
Set<String> sessionUploadFileSet = null;
Cache cache = cacheManager.getCache(RedissonCacheConfig.CacheEnum.UPLOAD_FILENAME_CACHE.name());
Cache.ValueWrapper valueWrapper = cache.get(TokenData.takeFromRequest().getSessionId());
if (valueWrapper != null) {
sessionUploadFileSet = (Set<String>) valueWrapper.get();
}
if (sessionUploadFileSet == null) {
sessionUploadFileSet = new HashSet<>();
}
sessionUploadFileSet.add(filename);
cache.put(TokenData.takeFromRequest().getSessionId(), sessionUploadFileSet);
}
}
/**
* 判断参数中的文件名是否有当前session上传。
*
* @param filename 通常是本地存储的文件名,而不是上传时的原始文件名。
* @return true表示该文件是由当前session上传并存储在本地的否则false。
*/
public boolean existSessionUploadFile(String filename) {
if (filename == null) {
return false;
}
Cache cache = cacheManager.getCache(RedissonCacheConfig.CacheEnum.UPLOAD_FILENAME_CACHE.name());
Cache.ValueWrapper valueWrapper = cache.get(TokenData.takeFromRequest().getSessionId());
if (valueWrapper == null) {
return false;
}
return ((Set<String>) valueWrapper.get()).contains(filename);
}
/**
* 清除当前session的所有缓存数据。
*
* @param sessionId 当前会话的SessionId。
*/
public void removeAllSessionCache(String sessionId) {
for (RedissonCacheConfig.CacheEnum c : RedissonCacheConfig.CacheEnum.values()) {
cacheManager.getCache(c.name()).evict(sessionId);
}
}
}

View File

@@ -0,0 +1,102 @@
package com.orange.demo.common.redis.config;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.orange.demo.common.core.exception.InvalidRedisModeException;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Redisson配置类。
*
* @author Jerry
* @date 2020-09-24
*/
@Configuration
@ConditionalOnProperty(name = "redis.redisson.enabled", havingValue = "true")
public class RedissonConfig {
@Value("${redis.redisson.lockWatchdogTimeout}")
private Integer lockWatchdogTimeout;
@Value("${redis.redisson.mode}")
private String mode;
/**
* 仅仅用于sentinel模式。
*/
@Value("${redis.redisson.masterName:}")
private String masterName;
@Value("${redis.redisson.address}")
private String address;
@Value("${redis.redisson.timeout}")
private Integer timeout;
@Value("${redis.redisson.password:}")
private String password;
@Value("${redis.redisson.pool.poolSize}")
private Integer poolSize;
@Value("${redis.redisson.pool.minIdle}")
private Integer minIdle;
@Bean
public RedissonClient redissonClient() {
if (StrUtil.isBlank(password)) {
password = null;
}
Config config = new Config();
if ("single".equals(mode)) {
config.setLockWatchdogTimeout(lockWatchdogTimeout)
.useSingleServer()
.setPassword(password)
.setAddress(address)
.setConnectionPoolSize(poolSize)
.setConnectionMinimumIdleSize(minIdle)
.setConnectTimeout(timeout);
} else if ("cluster".equals(mode)) {
String[] clusterAddresses = StrUtil.splitToArray(address, ',');
config.setLockWatchdogTimeout(lockWatchdogTimeout)
.useClusterServers()
.setPassword(password)
.addNodeAddress(clusterAddresses)
.setConnectTimeout(timeout)
.setMasterConnectionPoolSize(poolSize);
} else if ("sentinel".equals(mode)) {
String[] sentinelAddresses = StrUtil.splitToArray(address, ',');
config.setLockWatchdogTimeout(lockWatchdogTimeout)
.useSentinelServers()
.setPassword(password)
.setMasterName(masterName)
.addSentinelAddress(sentinelAddresses)
.setConnectTimeout(timeout)
.setMasterConnectionPoolSize(poolSize);
} else if ("master-slave".equals(mode)) {
String[] masterSlaveAddresses = StrUtil.splitToArray(address, ',');
if (masterSlaveAddresses.length == 1) {
throw new IllegalArgumentException(
"redis.redisson.address MUST have multiple redis addresses for master-slave mode.");
}
String[] slaveAddresses = new String[masterSlaveAddresses.length - 1];
ArrayUtil.copy(masterSlaveAddresses, 1, slaveAddresses, 0, slaveAddresses.length);
config.setLockWatchdogTimeout(lockWatchdogTimeout)
.useMasterSlaveServers()
.setPassword(password)
.setMasterAddress(masterSlaveAddresses[0])
.addSlaveAddress(slaveAddresses)
.setConnectTimeout(timeout)
.setMasterConnectionPoolSize(poolSize);
} else {
throw new InvalidRedisModeException(mode);
}
return Redisson.create(config);
}
}

View File

@@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.orange.demo.common.redis.config.RedissonConfig