本文作者:云初冀北

springboot整合单机缓存ehcache的实现

springboot整合单机缓存ehcache的实现摘要: 区别于redis的分布式缓存,ehcache是纯java进程内的单机缓存,根据不同的场景可选择使用,以下内容主要为springboot整合ehcache以及注意事项添加pom引用n...

?=区别于Redis分布式缓存ehcache是纯Java进程内的单机缓存,根据不同的场景可选择使用,以下内容主要为springboot整合ehcache以及注意事项

添加Pom引用

<dependency> <grouPID>.net.sf.ehcache</groupID> <artifactId>ehcache</artifactId> <versiON>2.10.9.2</version> </dependency>

启动添加开启缓存注解:@EnableCaching

添加xml配置,注意,ehcache需要单独的配置文件

<?xml version="1.0" encoDIng="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"  updateCheck="false">   <!--默认缓存策略 --> <!-- external:是否永久存在,设置为true则不会被清除,此时与timeout冲突,通常设置为false--> <!-- diskPersistent:是否启用磁盘持久化--> <!-- maxElemenTSInmemory:最大缓存数量--> <!-- overflowToDisk:超过最大缓存数量是否持久化到磁盘--> <!-- timeToIdleSeconds:最大不活动间隔,设置过长缓存容易溢出,设置过短无效果,可用于记录时效性数据,例如验证码--> <!-- timeToLiveSeconds:最大存活时间--> <!-- memoryStoreEvictionPolicy:缓存清除策略--> <defaultCache eternal="false" diskPersistent="false" maxElementsInMemory="1000" overflowToDisk="false" timeToIdleSeconds="60" timeToLiveSeconds="60" memoryStoreEvictionPolicy="LRU" />     <cache name="cache1"    eternal="false"    diskPersistent="false"    maxElementsInMemory="1000"    overflowToDisk="false"    timeToIdleSeconds="2"    timeToLiveSeconds="2"    memoryStoreEvictionPolicy="LRU" /> </ehcache>

这里我定义了一个缓存名字为cache1

修改项目的配置文件application.properties,添加spring缓存类型以及缓存配置文件路径

spring.cache.ehcache.config=classpath:ehcache.xml spring.cache.type=ehcache

上面的步骤做好之后,就可以使用了

给你需要加缓存的方法添加注解

@Configuration public class testConfig {   @Cacheable(value = "cache1",key = "#id") public TestController.Person create(string id) { return new TestController.Person(); } }

这里的value跟xml配置文件里的一致即可

我们调用一下测试看看

@GetMapping("/testCache1") public void testCache1(@Param("id") String id) throws interruptedException { Person obj1 = testConfig.create(id); Person obj2 = testConfig.create(id); Thread.sleep(3000); Person obj3 = testConfig.create(id); Person obj4 = testConfig.create(id);   log.info("test1:"+obj1.tostring()); log.info("test2:"+obj2.toString()); log.info("test3:"+obj3.toString()); log.info("test4:"+obj4.toString()); System.out.println(obj1.equals(obj2)); }

一下结果看

springboot整合单机缓存ehcache的实现

可以看到,obj1跟obj2是同一个对象,当程序睡眠了三秒之后,再次调用方法,就会重新创建对象,缓存生效

注意事项:

@Cacheable修饰的方法必须是public并且不能是static,原理是因为使用了动态代理,需要重写方法

xml里面的配置要写全,要不然项目启动报错,就是下图这些

springboot整合单机缓存ehcache的实现

xml里面配置的defaultCache没看出有啥用,我也没删了试试

使用缓存的方法不能在@RestController修饰的类中,即不能在controller层,要不然缓存失效,可以在@Service、@Configuratin、@Component等类下面

到此这篇关于springboot整合单机缓存ehcache的实现的文章就介绍到这了,更多相关springboot单机缓存ehcache内容请搜索云初冀北以前的文章或继续浏览下面的相关文章希望大家以后多多支持云初冀北!

免责声明
本站提供的资源,都来自网络,版权争议与本站无关,所有内容及软件的文章仅限用于学习和研究目的。不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负,我们不保证内容的长久可用性,通过使用本站内容随之而来的风险与本站无关,您必须在下载后的24个小时之内,从您的电脑/手机中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。侵删请致信E-mail:Goliszhou@gmail.com
$

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享

发表评论

快捷回复:

评论列表 (暂无评论,208人围观)参与讨论

还没有评论,来说两句吧...