|
|
|
@ -0,0 +1,87 @@
|
|
|
|
|
/*
|
|
|
|
|
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
|
|
|
|
|
*
|
|
|
|
|
* https://www.mall4j.com/
|
|
|
|
|
*
|
|
|
|
|
* 未经允许,不可做商业用途!
|
|
|
|
|
*
|
|
|
|
|
* 版权所有,侵权必究!
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
package com.yami.shop.common.util;
|
|
|
|
|
|
|
|
|
|
import lombok.AllArgsConstructor;
|
|
|
|
|
import org.springframework.cache.Cache;
|
|
|
|
|
import org.springframework.cache.CacheManager;
|
|
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* CacheManagerUtil类用于方便地操作Spring的缓存机制。
|
|
|
|
|
* 它依赖于Spring的CacheManager来获取、设置和清除缓存中的数据,
|
|
|
|
|
* 提供了对缓存数据进行增删查操作的便捷方法。
|
|
|
|
|
* 该类被声明为Spring的一个组件(@Component注解),可以被自动注入到其他需要使用缓存操作功能的类中。
|
|
|
|
|
*
|
|
|
|
|
* @author lanhai
|
|
|
|
|
*/
|
|
|
|
|
@Component
|
|
|
|
|
@AllArgsConstructor
|
|
|
|
|
public class CacheManagerUtil {
|
|
|
|
|
|
|
|
|
|
// Spring的缓存管理器,用于获取具体的缓存对象等操作,通过构造注入的方式获取
|
|
|
|
|
private CacheManager cacheManager;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 从指定名称的缓存中根据给定的键获取缓存值。
|
|
|
|
|
*
|
|
|
|
|
* @param <T> 泛型参数,表示期望获取的缓存值的类型。
|
|
|
|
|
* @param cacheName 缓存的名称,用于通过CacheManager定位到具体的缓存对象。
|
|
|
|
|
* @param key 缓存中数据对应的键,用于在具体缓存对象里查找对应的值。
|
|
|
|
|
* @return 如果缓存中存在对应键的值,则返回该值(转换为指定的泛型类型T),若缓存不存在或者对应键的值不存在,则返回null。
|
|
|
|
|
*/
|
|
|
|
|
@SuppressWarnings({"unchecked"})
|
|
|
|
|
public <T> T getCache(String cacheName, String key) {
|
|
|
|
|
// 通过缓存管理器获取指定名称的缓存对象
|
|
|
|
|
Cache cache = cacheManager.getCache(cacheName);
|
|
|
|
|
if (cache == null) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
// 从缓存对象中尝试获取对应键的值的包装对象
|
|
|
|
|
Cache.ValueWrapper valueWrapper = cache.get(key);
|
|
|
|
|
if (valueWrapper == null) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
// 从包装对象中获取实际的值,并转换为指定的泛型类型T返回
|
|
|
|
|
return (T) valueWrapper.get();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 将给定的值存入指定名称的缓存中,对应给定的键。
|
|
|
|
|
*
|
|
|
|
|
* @param cacheName 缓存的名称,用于通过CacheManager定位到要操作的具体缓存对象。
|
|
|
|
|
* @param key 缓存中数据对应的键,用于标识存入的值在缓存中的位置。
|
|
|
|
|
* @param value 要存入缓存的值,其类型可以是任意符合缓存要求的Java对象。
|
|
|
|
|
*/
|
|
|
|
|
public void putCache(String cacheName, String key, Object value) {
|
|
|
|
|
// 通过缓存管理器获取指定名称的缓存对象
|
|
|
|
|
Cache cache = cacheManager.getCache(cacheName);
|
|
|
|
|
if (cache!= null) {
|
|
|
|
|
// 如果缓存对象存在,则将键值对存入该缓存对象中
|
|
|
|
|
cache.put(key, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 从指定名称的缓存中清除对应给定键的缓存数据。
|
|
|
|
|
*
|
|
|
|
|
* @param cacheName 缓存的名称,用于通过CacheManager定位到要操作的具体缓存对象。
|
|
|
|
|
* @param key 缓存中数据对应的键,用于确定要清除的缓存数据。
|
|
|
|
|
*/
|
|
|
|
|
public void evictCache(String cacheName, String key) {
|
|
|
|
|
// 通过缓存管理器获取指定名称的缓存对象
|
|
|
|
|
Cache cache = cacheManager.getCache(cacheName);
|
|
|
|
|
if (cache!= null) {
|
|
|
|
|
// 如果缓存对象存在,则清除对应键的缓存数据
|
|
|
|
|
cache.evict(key);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|