spring-boot ehcase 缓存

1.spring-boot中整合ehcase缓存

引入依赖,ehcase,spring-boot对缓存的支持,和测试的依赖支持

<!-- springBoot junit的启动器 -->
		<dependency>
	  		<groupId>org.springframework.boot</groupId>
	       <artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<!-- Spring Boot缓存支持启动器 -->
		<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.添加ehcache.xml文件,在classPath目录  文件的内容参考ehcache的jar包中的配置

注意name属性很重要,不能重复

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 
 	<diskStore path="java.io.tmpdir"/>
   
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    
    <cache name="users"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
    
    
</ehcache>

3.spring-boot全局配置文件中配置cache配置文件的路径

spring.cache.ehcache.config=ehcache.xml

4.启动类上开启缓存

5.业务代码使用缓存机制  在方法上添加@Cacheable(value="users")

value的值是ehcache.xml文件中配置的name,没有value就用默认的缓存配置。

框架根据方法的参数做为一个key的一部分,返回值作为value。缓存好

如果返回值的对象没有实现序列号接口,需要实现下。

@Cacheable() 两个参数 value 使用缓存策略   key="#"   把什么作为缓存的key

@CacheEvict (value="users", allEntries=true)  清除缓存,一般有数据库操作后清除缓存。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值