ESCacheManager.java 1.92 KB
package com.zhaoonline.es.cache;

import java.util.Collection;
import java.util.Collections;

import org.springframework.cache.Cache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;
import org.springframework.cache.transaction.TransactionAwareCacheDecorator;

import com.zhaoonline.es.core.ESClient;

/**
 * class name:ESCacheManager <BR>
 * class description: ESCacheManager的作用是为了将Cache交给Spring来管理 <BR>
 * Remark: <BR>
 * @version 1.00 2016年8月23日
 * @author zhaoonline)yangyoupeng
 */
public class ESCacheManager extends AbstractTransactionSupportingCacheManager {
	private ESClient client=null;
	 public ESCacheManager(ESClient client) {
		this.client=client;
	}
	@Override
	public Cache getCache(String name) {
		Cache cache = super.getCache(name);
		if (cache == null ) {
			return createAndAddCache(name);
		}
		return cache;
	}
	
	@SuppressWarnings("deprecation")
	private Cache createAndAddCache(String cacheName) {
		addCache(createCache(cacheName));
		return super.getCache(cacheName);
	}

	protected ESCache createCache(String cacheName) {
		return new ESCache(cacheName,client);
	}
	

	/**
	 * @Override
	 * @see org.springframework.cache.support.AbstractCacheManager#loadCaches() <BR>
	 * Method name: loadCaches <BR>
	 * Description:这里我们创建一个emptyList <BR>
	 * Remark: <BR>
	 * @return  <BR>
	*/
	@Override
	protected Collection<? extends Cache> loadCaches() {
		return Collections.<Cache> emptyList();
	}

	/* (non-Javadoc)
	* @see
	org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager#decorateCache(org.springframework.cache.Cache)
	*/
	@Override
	protected Cache decorateCache(Cache cache) {
		if (isCacheAlreadyDecorated(cache)) {
			return cache;
		}
		return super.decorateCache(cache);
	}

	protected boolean isCacheAlreadyDecorated(Cache cache) {
		return isTransactionAware() && cache instanceof TransactionAwareCacheDecorator;
	}
}