很多时候一条操作链路上需要获取很多重复的基础信息,比如用户的信息,可能在AO层也有,Service 层也有,这样造成的问题是每次都需要发起一次调用(数据库 or RPC),这样造成的问题是对性能的无谓浪费,当然可以通过参数进行透传,但是这样带来的问题是必须修改方法的定义,一方面遗留代码需要大量修改,另一方面接口的参数也会极具庞大,特别是A->B->C ,这样的方法调用链,如果只有A和C用到了用户数据,B就算没用到也需要定义一个用户信息的入参,这个对接口的定义造成了很大的污染。
原来在mall的工程中为了解决user和shop的信息反复查询,结合spring的注解设计了TLCache,利用ThreadLocal的特性在一个线程内对adapter接口的返回值进行缓存,这样在同一个线程内对该接口的多次调用实际只会产生1次远程调用
@Override
@Cacheable(value = "TLCache", key ="'UserAdapter.getUserInfoById-' + (#userId)") //此处不能用本地缓存,redirect的登录拦截器会校验openId
public UserDTO getUserInfoById(String userId) {
因为ThreadLocal本身的特性,需要在合适的时间进行内存初始化和回收,否则会造成内存泄漏。如果使用dubbo,框架提供的filter 会自动进行处理,其他使用方式需要自己做一些设置。
直接引入依赖就可以自动加载 jar包中的DubboThreadLocalCacheFilter,做好初始化以及资源清理。
需要配置interceptor,在preHandle 方法中调用 TLCacheUtil.initThreadCache 进行初始化,然后在afterCompletion方法中调用方法中调用 TLCacheUtil.clearThreadCache
示例:
public class LocalThreadCache4ItemInterceptor implements HandlerInterceptor{
private static final Logger log = LoggerFactory.getLogger(LocalThreadCache4ItemInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
TLCacheUtil.initThreadCache();
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
TLCacheUtil.clearThreadCache();
}
}
需要保证在整个调用链之前进行初始化(TLCacheUtil.initThreadCache),在调用链结束之后进行清理(TLCacheUtil.clearThreadCache)。
spring cache 已经提供了非常好的配套,只需要实现他的Cache 接口就能享受到他提供的一套组件, 框架中的 ThreadLocalCache 已经实现。
<cache:annotation-driven/>
<bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
<property name="cacheManagers">
<list>
<ref bean="simpleCacheManager"/>
list>
property>
<property name="fallbackToNoOpCache" value="true"/>
bean>
<bean id="simpleCacheManager"
class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean name="TLCache" class="com.yt.asd.tl.cache.ThreadLocalCache" />
set>
property>
bean>
对具体接口的使用
@Override
@Cacheable(value = "TLCache", key ="'UserAdapter.getUserInfoById-' + (#userId)") //此处不能用本地缓存,redirect的登录拦截器会校验openId
public UserDTO getUserInfoById(String userId) {
****
****
}
TLCacheUtils 实现
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TLCacheUtil {
private static final Logger log = LoggerFactory.getLogger(TLCacheUtil.class);
private static ThreadLocal<SoftReference<Map<String, Object>>> threadLocalCache = new ThreadLocal();
public TLCacheUtil() {
}
public static void initThreadCache() {
SoftReference<Map<String, Object>> mapSoftReference = (SoftReference)threadLocalCache.get();
if (mapSoftReference == null) {
mapSoftReference = new SoftReference(new HashMap());
threadLocalCache.set(mapSoftReference);
}
}
public static void clearThreadCache() {
threadLocalCache.remove();
}
public static void setThreadCache(String prefix, String key, Object value) {
String cacheKey = prefix + key;
SoftReference<Map<String, Object>> mapSoftReference = (SoftReference)threadLocalCache.get();
if (mapSoftReference == null) {
log.error("[TLCacheUtil-setThreadCache]error,TLCache is not init,prefix={},key={}", prefix, key);
} else {
Map<String, Object> threadCache = (Map)mapSoftReference.get();
if (threadCache != null) {
threadCache.put(cacheKey, value);
}
}
}
public static Object getThreadCache(String prefix, String key) {
SoftReference<Map<String, Object>> mapSoftReference = (SoftReference)threadLocalCache.get();
if (mapSoftReference == null) {
return null;
} else {
Map<String, Object> threadCache = (Map)mapSoftReference.get();
String cacheKey = prefix + key;
return threadCache.get(cacheKey);
}
}
public static <T> T getThreadCache(String prefix, String key, T defVal) {
T val = defVal;
Object clientCodeObj = getThreadCache(prefix, key);
if (Objects.nonNull(clientCodeObj)) {
val = clientCodeObj;
}
return val;
}
}
结合spring使用的cache封装
import java.util.concurrent.Callable;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.support.SimpleValueWrapper;
public class ThreadLocalCache implements Cache {
public ThreadLocalCache() {
}
public String getName() {
return "TLCache";
}
public Object getNativeCache() {
return null;
}
public ValueWrapper get(Object key) {
Validate.notNull(key);
Object value = TLCacheUtil.getThreadCache("", key.toString());
return value == null ? null : new SimpleValueWrapper(value);
}
public <T> T get(Object key, Class<T> type) {
Validate.notNull(key);
Object value = TLCacheUtil.getThreadCache("", key.toString());
return value == null ? null : value;
}
public <T> T get(Object o, Callable<T> callable) {
throw new UnsupportedOperationException("未实现的方法");
}
public void put(Object key, Object value) {
Validate.notNull(key);
if (null != value) {
TLCacheUtil.setThreadCache("", key.toString(), value);
}
}
public ValueWrapper putIfAbsent(Object key, Object value) {
Validate.notNull(key);
Validate.notNull(value);
if (TLCacheUtil.getThreadCache("", key.toString()) == null) {
this.put(key, value);
}
return new SimpleValueWrapper(this.get(key));
}
public void evict(Object key) {
}
public void clear() {
}
}