Java的EhCache缓存框架

缓存配置文件

#=============================================================Cache Core config===============================================================
#缓存类型 ehcache,redis
core.cache.type=ehcache
#=============================================================redis  config===============================================================
#主机地址,默认:localhost
redis.ip=192.168.1.100
#主机端口,默认:6379
redis.port=10001
#超时时间,默认:2000
redis.timeout=3000
#登录认证
redis.password=cnten
#是否使用连接池,默认true
redis.usePool=true
#使用数据库的索引,0-15之间的数字,默认:0
redis.dbIndex=0

#最大连接数
redis.pool.maxTotal=30
#最大空闲
redis.pool.maxIdle=10
#每次最大连接数
redis.pool.numTestsPerEvictionRun=1024
#释放扫描的扫描间隔
redis.pool.timeBetweenEvictionRunsMillis=30000
#连接的最小空闲时间
redis.pool.minEvictableIdleTimeMillis=1800000
#连接空闲按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放
redis.pool.softMinEvictableIdleTimeMillis=10000
#获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1
redis.pool.maxWaitMillis=1500
#在获得链接的时候检查有效性,默认false
redis.pool.testOnBorrow=true
#在空闲时检查有效性,默认false
redis.pool.testWhileIdle=true
#连接耗尽时是否阻塞,false报异常,true阻塞超时,默认true
redis.pool.blockWhenExhausted=false

获取缓存配置文件

import com.cnten.platform.exception.CacheException;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Properties;

public class CacheConfig
{
  private static final String config_properties = CacheConfig.class.getResource("/").getPath() + "/config/cache.properties";
  private static Properties properties = getConfigFile();
  
  public static String get(String key)
  {
    return properties.getProperty(key);
  }
  
  public static Properties getConfigFile()
  {
    return getConfigFileProperties(config_properties);
  }
  
  public static Properties getConfigFileProperties(String fileName)
  {
    Properties configFile = new Properties();
    try
    {
      configFile.load(new FileInputStream(config_properties));
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new CacheException(e);
    }
    return configFile;
  }
}

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="defaultCache">

    <!-- 
		磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
		path:指定在硬盘上存储对象的路径
    -->
    <diskStore path="java.io.tmpdir/otc"/>

    <!-- 默认缓存配置. -->
    <defaultCache maxEntriesLocalHeap="100" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
                  overflowToDisk="true" maxEntriesLocalDisk="100000"/>
    
</ehcache>

缓存处理类

​
<bean id="ehCacheManagerImpl" class="com.cache.impl.EhCacheManagerImpl" lazy-init="false"/>
	<bean id="redisCacheManagerImpl" class="com.cache.impl.RedisCacheManagerImpl" lazy-init="false"/>
	<bean id="interceptorCacheManagerImpl" class="com..CntenInterceptorCacheManagerImpl" lazy-init="false"/>
	<bean id="cacheManager" class="net.sf.ehcache.CacheManager" lazy-init="false"/>
​
import com.cache.impl.EhCacheManagerImpl

    @Autowired
    private EhCacheManagerImpl ehCaheMamger;

   String appAccessToken = ehCaheMamger.get("accessToken", "appAccessToken");

    ehCaheMamger.put("accessToken", "appAccessToken", appAccessToken);

缓存工厂

import com.cache.config.CacheEnum;
import com.context.SpringContextHolder;

public final class CacheFactory
{
  public static ICacheManager getCache()
  {
    return getCache(CacheEnum.ehcache);
  }
  
  public static ICacheManager getCache(CacheEnum cacheType)
  {
    if (cacheType == null) {
      cacheType = CacheEnum.ehcache;
    }
    return (ICacheManager)SpringContextHolder.getBean(cacheType.getCacheType());
  }
}
public enum CacheEnum
{
  ehcache("ehCacheManagerImpl", "ehcache 实现"),  redis("redisCacheManagerImpl", "redis 实现");
  
  private String cacheType;
  private String cacheDesc;
  
  private CacheEnum(String cacheType, String cacheDesc)
  {
    this.cacheType = cacheType;
    this.cacheDesc = cacheDesc;
  }
  
  public String getCacheType()
  {
    return this.cacheType;
  }
  
  public String getCacheDesc()
  {
    return this.cacheDesc;
  }

缓存接口

public abstract interface ICacheManager
{
  public abstract <T> T get(String paramString, Object paramObject);
  
  public abstract void put(String paramString, Object paramObject1, Object paramObject2);
  
  public abstract void remove(String paramString, Object paramObject);
  
  public abstract void removeAll(String paramString);
}

同步缓存数据

private ICacheManager cacheManager = CacheFactory.getCache();
private static final String CONFIG_CACHE_KEY = "config_cache_key";
	/**
	 * 获取有效的配置
	 * @return
	 */
	public List<Config> getValidConfigs(){
		Config config = new Config();
		config.setState(Constant.NUMBER_INTEGER_1);
		List<Config> list = configMapper.getAllConfigs(config);
		
		//同时更新缓存
		if(list != null) {
			cacheManager.remove(CONFIG_CACHE_KEY, CONFIG_CACHE_KEY);
			cacheManager.put(CONFIG_CACHE_KEY, CONFIG_CACHE_KEY, list);
		}
		
		return list;
	}
updateCacheConfig(config);		//同步缓存中的数据
	private void updateCacheConfig(Config config) {
		List<Config> configs = cacheManager.get(Config.class.getName(), CONFIG_CACHE_KEY);
		
		Iterator<Config> it = configs.iterator();
		
		while(it.hasNext()) {
			Config confItem = it.next();
			if(confItem.getConfId().equals(config.getConfId())) {
				it.remove();
			}
		}
		
		configs.add(config);
	}

removeCacheConfig(ids);			//同时删除缓存中的数据
	private void removeCacheConfig(List<String> confIds) {
		List<Config> configs = cacheManager.get(Config.class.getName(), CONFIG_CACHE_KEY);
		Iterator<Config> it = configs.iterator();
		for (String sItem : confIds) {
			while(it.hasNext()) {
				Config confItem = it.next();
				if(sItem.equals(confItem.getConfId())) {
					it.remove();
				}
			}
		}
	}


缓存实现类

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;

public class EhCacheManagerImpl
  implements ICacheManager
{
  public static final CacheManager cacheManager = (CacheManager)SpringContextHolder.getBean("cacheManager");
  
  protected static CacheManager getCacheManager()
  {
    return cacheManager;
  }
  
  private static synchronized Cache getCache(String cacheName)
  {
    Cache cache = getCacheManager().getCache(cacheName);
    if (cache == null)
    {
      getCacheManager().addCache(cacheName);
      cache = getCacheManager().getCache(cacheName);
      cache.getCacheConfiguration().setEternal(true);
    }
    return cache;
  }
  
  public <T> T get(String cacheName, Object key)
  {
    Element element = getCache(cacheName).get(key);
    return element == null ? null : element.getObjectValue();
  }
  
  public void put(String cacheName, Object key, Object value)
  {
    Element element = new Element(key, value);
    getCache(cacheName).put(element);
  }
  
  public void remove(String cacheName, Object key)
  {
    getCache(cacheName).remove(key);
  }
  
  public void removeAll(String cacheName)
  {
    Cache cache = getCacheManager().getCache(cacheName);
    cache.removeAll(true);
  }
}

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/82555246