@Cacheable缓存使用

本文介绍了如何在SpringBoot应用中使用@Cacheable注解实现内存缓存和Redis分布式缓存。首先,需要引入相关jar包并配置缓存策略,包括缓存方式和生存周期。接着,讲解了配置ehcache.xml和CacheConfig,以及编写EhCachePolicyProvider和EhCacheInitializer。最后,通过在方法上添加@Cacheable注解,实现缓存功能。详情可参考提供的优快云博客链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可实现内存缓存,redis缓存(分布式应用).

大前提,启动类上开启缓存

1.引jar包

<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-cache -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

2.编写配置文件

配置缓存策略:缓存方式+生存周期

(1) ehcache.xml

<?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">
    <!-- EhCache在每次启动的时候都要连接到 ehcache 网站上去检查新版本 使用如上的 updateCheck="false" 来禁止这个检查新版本 -->
    
    <!--  
        name:cache唯一标识   
        eternal:缓存是否永久有效   
        maxElementsInMemory:内存中最大缓存对象数  
        overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中  
        diskPersistent:硬盘持久化  
        timeToIdleSeconds:缓存清除时间   
        timeToLiveSeconds:缓存存活时间
        diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔
        memoryStoreEvictionPolicy:缓存清空策略
        1.FIFO:first in first out 先讲先出  
        2.LFU: Less Frequently Used 一直以来最少被使用的  
        3.LRU:Least Recently Used  最近最少使用的   
    -->
    
    <diskStore path="java.io.tmpdir/ehcache" />
    
    <defaultCache 
        maxElementsInMemory="10000" 
        eternal="false" 
        timeToIdleSeconds="120"
        timeToLiveSeconds="120" 
        overflowToDisk="true" 
        maxElementsOnDisk="10000000"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" 
        memoryStoreEvictionPolicy="FIFO" />

    <!-- 缓存  -->
    <cache name="cache_mall_keys"
       maxElementsInMemory="200"
       eternal="false"
       timeToIdleSeconds="7200"
       timeToLiveSeconds="7200"
       overflowToDisk="true"
       maxElementsOnDisk="1000"
       diskPersistent="false"
       diskExpiryThreadIntervalSeconds="120"
       memoryStoreEvictionPolicy="FIFO" />

    <!-- 缓存  -->
    <cache name="cache_pos_codes"
           maxElementsInMemory="200"
           eternal="false"
           timeToIdleSeconds="43200"
           timeToLiveSeconds="43200"
           overflowToDisk="true"
           maxElementsOnDisk="1000"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="FIFO" />
        
</ehcache> 

(2) CacheConfig配置文件

@Configuration
public class CacheConfig{

    public interface CacheManagerName{
        String REDIS_CACHE_MANAGER = "redisCacheManager";
        String EHCACHE_CACHE_MANAGER = "ehCacheCacheManager";
    }

    @Bean(CacheConfig.CacheManagerName.EHCACHE_CACHE_MANAGER)
    @Primary
    public EhCacheCacheManager EhCacheManager(){
        return new EhCacheCacheManager();
    }

    @Bean(第一个name)
    public RedisCacheManager cacheManager(RedisConnectionFactory fact){
        return new RedisCacheManager(
            RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
            this.getRedisCacheConfigurationWithTtl(3600),
            this.getRedisCacheConfigurationMap()
        );
    }

    private Map<String,RedisCacheConfiguration> getRedisCacheConfigurationMap(){
        return new HashMap<>(){{put("一个配置名称",this.getRedisCacheConfiguration.defaultConfig())}};
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds){
        RedisCacheConfiguration cofig = RedisCacheConfiguration.defaultCacheConfig();
        cofig = cofig.entryTtl9Duration.ofSeconds(seconds));
        return cofig;
    }
}

3.编写EhCachePolicyProvider

public interface EhCachePolicyProvider{
    void buildOnStartUp();
    void refresh();
}

编写EhCacheInitializer类

public class EhCacheInitializer implements ApplicationListener<ApplicationReadyEvent>{

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent){
        List<EhCachePolicyProvider> providers = SpringContext.getBeanList(EhCachePolicyProvider.class);
        providers.parallelStream().forEach(EhCachePolicyProvider::buildOnStartUp);
    }
}

4.在方法上加@Cacheable注解

具体写法参考如下链接:

https://blog.youkuaiyun.com/BinshaoNo_1/article/details/84579326

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值