Ehcache 工具类 [ EhCacheUtil ]
<dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.5.0</version> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <config xmlns="http://www.ehcache.org/v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"> <!-- 缓存模板 --> <cache-template name="cacheTemplate"> <key-type>java.lang.String</key-type> <value-type>java.lang.String</value-type> <heap unit="entries">200</heap> </cache-template> <!-- 无到期时间的缓存 --> <cache alias="noExpiryCache" uses-template="cacheTemplate"> <expiry> <!-- 永久有效 --> <none/> </expiry> </cache> <!-- 有到期时间的缓存 --> <cache alias="expiryCache" uses-template="cacheTemplate"> <expiry> <!-- 10分钟后无访问将过期 --> <tti unit="minutes">10</tti> </expiry> </cache> </config>
package com.app.core.util; import org.ehcache.Cache; import org.ehcache.Cache.Entry; import org.ehcache.CacheManager; import org.ehcache.config.Configuration; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.xml.XmlConfiguration; import java.net.URL; import java.util.HashMap; import java.util.Map; public class EhCacheUtil { /** * 缓存管理器 */ private static CacheManager cacheManager = null; /** * 无到期时间的缓存域 */ public static Cache<String, String> noExpiryCache = null; /** * 有到期时间的缓存域,有效期:10分钟 */ public static Cache<String, String> expiryCache = null; static { // 获取ehcache配置文件路径 URL url = EhCacheUtil.class.getResource("/config/ehcache.xml"); // 加载ehcache配置文件 Configuration xmlConfig = new XmlConfiguration(url); // 获取ehcache管理器 cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); // 初始化ehcache管理器 cacheManager.init(); // 获取无到期时间的缓存域 noExpiryCache = getCache("noExpiryCache", String.class, String.class); // 获取有到期时间的缓存域,有效期:10分钟 expiryCache = getCache("noExpiryCache", String.class, String.class); } /** * 获取EhCahce缓存域 * * @param alias 缓存域名称 * @param keyType 键类型 * @param valueType 值类型 * @return */ public static <K, V> Cache<K, V> getCache(String alias, Class<K> keyType, Class<V> valueType) { return cacheManager.getCache(alias, keyType, valueType); } /** * 获取缓存域中的所有键值对 * * @return */ public static <K, V> Map<K, V> iterator(Cache<K, V> cache) { Map<K, V> map = null; if (cache != null) { map = new HashMap<K, V>(); // 循环取出缓存域中的键和值 for (Entry<K, V> entry : cache) map.put(entry.getKey(), entry.getValue()); } return map; } }
相关推荐
-
JSON工具类 java
2019-1-12
-
opencsv 工具类 [ CsvUtil ] java
2019-1-12
-
阿里云短信接口工具类 java
2019-1-13
-
StringUtils工具类介绍 java
2019-1-13
-
MySQL通用性较高的分页代码 java
2019-1-13
-
将数据库对应的表生成对应的实体类,包含注释信息 java
2019-1-7
-
SpringMvc执行流程 java
2019-1-8
-
使用poi将excel转换为html,适用本身有导出excel的而现在需要添加网页打印的功能 java
2019-1-8
-
java根据经纬度计算两点之间距离 java
2019-1-8
-
删除 java代码中所有的注释 java
2019-1-7