Springboot 启用 ehcache缓存

首先,添加依赖

<!-- 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>

创建ehcache.xml配置文件

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" 
         updateCheck="false">
 
    <diskStore path="java.io.tmpdir/my-project-name"/>
 
    
    <!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 -->
    <!-- maxElementsInMemory: 在内存中缓存的element的最大数目。-->
    <!-- eternal:elements是否永久有效,如果为true,timeouts将被忽略,element将永不过期 -->
    <!-- timeToIdleSeconds:失效前的空闲秒数,当eternal为false时,这个属性才有效,0为不限制 -->
    <!-- timeToLiveSeconds:失效前的存活秒数,创建时间到失效时间的间隔为存活时间,当eternal为false时,这个属性才有效,0为不限制 -->
    <!-- overflowToDisk: 如果内存中数据超过内存限制,是否要缓存到磁盘上 -->
    <!-- statistics:是否收集统计信息。如果需要监控缓存使用情况,应该打开这个选项。默认为关闭(统计会影响性能)。设置statistics="true"开启统计 -->
    <!-- overflowToDisk和diskPersistent、DiskStoreBootstrapCacheLoaderFactory是在2.5及之前版本拥有的参数;
            2.6及之后的版本建议使用<persistence>或<terracotta>来代替,参阅ehcache.xsd。
            <persistence strategy="localTempSwap"/>
            或
            <persistence strategy="none"/>
            
        With the "localTempSwap" strategy, you can use maxEntriesLocalDisk or
        maxBytesLocalDisk at either the Cache or CacheManager level to control the
        size of the disk tier.
        
        When the persistence strategy is "none", all cache stays in memory (with
        no overflow to disk nor persistence on disk).
    -->
    <!--defaultCache:echcache的默认缓存策略  -->
    <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>

修改springboot配置文件,引入ehcache.xml配置文件

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

启用@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class Application{
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

实体类实现可序列化接口Serializable

由于需要实体类支持缓存中的磁盘存储,所以需要实体类实现可序列化接口。

public class User implements Serializable{ 
    ...
}

添加缓存注解@Cacheable@CacheEvict

@Cacheable缓存数据

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Cacheable(value="users")
    public User selectUserById(int id) {
        User user=this.userMapper.selectUserById(id);
        System.out.println("load data from db");
        return user;
    }
}

@CacheEvict清除缓存

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Cacheable(value="users")
    public User selectUserById(int id) {
        User user=this.userMapper.selectUserById(id);
        System.out.println("load data from db");
        return user;
    }
    
	@CacheEvict(value="users", allEntries=true)
	public void saveUsers(Users users) {
		this.userMapper.save(users);
	}
	
	@CacheEvict(value="users", allEntries=true)
	public void deleteUserById(int id) {
		this.userMapper.deleteUserById(id);
	}
}

其它

设置java.io.tmpdir子目录

<diskStore path="java.io.tmpdir/xxx"/>

参考

https://www.cnblogs.com/xzmiyx/p/9897623.html
https://blog.csdn.net/qq_33285292/article/details/108152912

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值