springboot Ehcache使用
1.Ehcache简单说明及使用 EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。 Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。 Ehcache最初是由Greg Luck于2003年开始开发。2009年,该项目被Terracotta购买。软件仍然是开源,但一些新的主要功能(例如,快速可重启性之间的一致性 的)只能在商业产品中使用,例如Enterprise EHCache and BigMemory。,维基媒体Foundationannounced目前使用的就是Ehcache技术。 Ehcache2.6.6 源码和jar包下载地址:https://oss.sonatype.org/content/repositories/sourceforge-releases/net/sf/ehcache/ehcache-core/2.6.6/ 2.1 添加依赖 ```xml <!-- 缓存 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 2.2 加入注解 @EnableCaching ```java @SpringBootApplication @EntityScan(basePackages ={ "entity","com.holworth.domain"}) @EnableCaching public class domainApplication {} ``` 2.3 EhCache配置 在src\main\resources目录下,添加ehcache.xml文件, ```xml <?xml version="1.0" encoding="UTF-8" ?> <ehcache> <cache name="objectCache" maxElementsInMemory="10000"></cache> </ehcache> ``` 2.4 application.application配置 # 配置ehcache缓存 spring.cache.type=ehcache # 指定ehcache配置文件路径 spring.cache.ehcache.config=classpath:/ehcache.xml 2.5 ```java package com.holworth.domain; import entity.BasCurrency; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cache.Cache; import org.springframework.cache.annotation.EnableCaching; import util.HraUtility; import org.springframework.cache.CacheManager; import javax.annotation.Resource; import java.util.List; @SpringBootApplication @EntityScan(basePackages ={ "entity","com.holworth.domain"}) @EnableCaching public class domainApplication { @Resource private CacheManager cacheManager; // @Autowired // private static com.holworth.domain.dao.a commonService; public static void main(String[] args) { //http://localhost:8086/MKT/MktRiskPriceManage.html //http://localhost:8080/api/RiskFactor/GetRiskFactor SpringApplication.run(domainApplication.class); CacheManager cacheManager = (CacheManager) SpringContextUtils.getBean("CacheManager"); Cache cache = cacheManager.getCache("objectCache"); cache.put("key", "123"); System.out.println("缓存成功"); String res = cache.get("key", String.class); System.out.println(res); } } ```