首先可以MemCache超详细解读
再看看Spring Cache介绍
Spring Cache默认使用了ConcurrentHashMap和Ehcache来实现. 想要转成Memcached, 得自己重写.
实现的方法也很简单, 只需写两个类, 一个继承org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager 抽象类, 用来管理Cache实例; 另一个类实现org.springframework.cache.Cache接口, 用来封装具体的缓存操作.
对Memcached来说, 它不像Ehcache一样可以有很多Cache实例, 且每个Cache实例都是独立的. 可以把Memcache看成只有一个Cache实例, 所有的缓存都储存在这个Cache实例里. 但是, Spring Cache对Cache的管理又是分Cache实例的, 它要求把缓存的内容放在某个Cache里, 如:
@Cacheable(value="userCache", key="#root.methodName")
public List getUsers();
它会把得到的结果放在名字为"userCache"的Cache里.
所以, 我们重写AbstractTransactionSupportingCacheManager的实现类时, 要模拟把Memcached分成多个Cache.
package com.demo.cache;
import com.whalin.MemCached.MemCachedClient;
import org.springframework.cache.Cache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
public class MemCachedCacheManager extends AbstractTransactionSupportingCacheManager {
private ConcurrentHashMap cacheMap = new ConcurrentHashMap(); //管理不同的Cache
private MemCachedClient memCachedClient; //memcached的客户端
public void setMemCachedClient(MemCachedClient memCachedClient) {
this.memCachedClient = memCachedClient;
}
@Override
protected Collection extends Cache> loadCaches() {
return cacheMap.values();
}
@Override
public Cache getCache(String name) {
Cache cache = cacheMap.get(name);
if (cache == null) {
cache = new MemCachedCache(name, memCachedClient);
cacheMap.put(name, cache);
}
return cache;
}
}
上面用一个ConcurrentHashMap来存放不同的Cache.
package com.demo.cache;
import com.whalin.MemCached.MemCachedClient;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import java.util.HashSet;
import java.util.Set;
public class MemCachedCache implements Cache {
private String cacheName; // 用名字来区分每个Cache
private Set keySet = new HashSet(); // 存放在这个Cache里的所有key
private MemCachedClient memCachedClient; // memcached客户端
public MemCachedCache(String cacheName, MemCachedClient cache) {
this.cacheName = cacheName;
this.memCachedClient = cache;
}
// 用cacheName+keyName的方式区分这个key是放在哪个Cache里
private String getKey(Object key) {
return this.cacheName + "_" + key.toString();
}
@Override
public String getName() {
return this.cacheName;
}
@Override
public Object getNativeCache() {
return this.memCachedClient;
}
@Override
public ValueWrapper get(Object key) {
Object val = memCachedClient.get(getKey(key));
return val != null ? new SimpleValueWrapper(val) : null;
}
@Override
public T get(Object key, Class type) {
Object val = memCachedClient.get(getKey(key));
if (val != null && type != null && !type.isInstance(val)) {
throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + val);
}
return val != null ? (T)val : null;
}
@Override
public void put(Object key, Object value) {
this.keySet.add(key.toString());
memCachedClient.set(getKey(key), value);
}
@Override
public void evict(Object key) {
this.keySet.remove(key.toString());
memCachedClient.delete(getKey(key));
}
// 当清理某个Cache时, 只清理这个Cache里的所以缓存, 不影响其他Cache
@Override
public void clear() {
for (String key : this.keySet) {
this.evict(key);
}
}
}
这里有一个地方要注意, 当我们把内容放进某一个Cahce里后, 重启tomcat, 然后再用相同的key去缓存里找, 能不能找到对应的内容? 答案是可以. 因为即使重启tomcat, cacheMap里所有的Cache实例都清空了, 但内存里的缓存内容没有消失, 它还在内存里. 当我们用key去搜时, MemCachedCacheManager会生成一个新的Cache实例, 放在cacheMap里, 但具体找缓存的操作, 是交给memCachedClient去做的, 它会根据key值(cacheName+keyName)去内存里找, 所以最后还是能找到. 从这个角度来看, 其实MemCachedCacheManager里的cacheMap是没有多大用处的, 它只是应Spring Cache管理Cache的要求而必须创建出来而已.
但这会引出另一个问题, 就是重启tomcat以后, 旧缓存的删除功能已经没法作用了, 因为cacheMap里面的cache会清空, 所以cache里面的keySet也会被清空. 所以, 当重启tomcat之后, 到底要不要保留旧缓存, 取决于业务逻辑. 如果要删除, 则重写ContextLoaderListener的contextDestroy()方法, 在里面进行删除. 如:
@Override
public void contextDestroyed(ServletContextEvent event) {
if (logger.isDebugEnabled()) {
logger.debug("******************* contextDestroying...");
}
// delete all cache in memcache when stop tomcat
removeCache(event);
super.contextDestroyed(event);
}
private void removeCache(ServletContextEvent event) {
WebApplicationContext webAppCxt = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
MemCachedCacheManager memCachedCacheManager = webAppCxt.getBean("memCacheManager", MemCachedCacheManager.class);
if (memCachedCacheManager != null) {
ConcurrentHashMap cacheMap = memCachedCacheManager.getCacheMap();
for (Cache cache : cacheMap.values()) {
if (logger.isDebugEnabled()) {
logger.debug("clearing cache: " + cache.getName());
}
cache.clear();
}
}
}
下面是Spring的配置文件
${memcache.server1}
${memcache.server2}
${memcache.initConn}
${memcache.minConn}
${memcache.maxConn}
${memcache.maintSleep}
${memcache.nagle}
${memcache.socketTO}