Springboot本地缓存带过期(名称分割-基于Caffeine-无Redis)

本文介绍了如何在SpringBoot应用中使用Caffeine库实现注解式缓存,包括设置过期时间和使用`@Cacheable`注解控制缓存策略,以及如何通过LocalCacheInit进行初始化和LocalCacheService中的方法缓存示例。
摘要由CSDN通过智能技术生成

实现思路:

1、使用注解@Cacheable的属性 cacheNames 来传输 过期时间,格式:name#expireTime

2、然后由 LocalCacheInit 解析注解,后构建支持过期的缓存管理器 CaffeineCacheManager

3、为需要缓存值的方法添加注解 @Cacheable,unless = "#result==null"表示值为空时不缓存

4、写测试方法,定时查看请求结果是否达到预期

5、启用缓存 @EnableCaching、启用定时@EnableScheduling

      定时示例:@Scheduled(cron = "*/1 * * * * *") 每秒一次

添加依赖 pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


        <!-- localCache -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>

 注册缓存

import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * LocalCacheInit
 *
 * @Date: 2024-1-12 17:35
 * @Author: 
 * @Version: 1.0
 */
@Slf4j
@Component
@EnableCaching
public class LocalCacheInit implements SmartInitializingSingleton, BeanFactoryAware {
    private DefaultListableBeanFactory beanFactory;

    @Autowired
    CaffeineCacheManager caffeineCacheManager;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory)beanFactory;
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, Object> beansWithAnnotation = beanFactory.getBeansWithAnnotation(Component.class);
        if(MapUtils.isNotEmpty(beansWithAnnotation)){
            for (Object cacheValue : beansWithAnnotation.values()) {
                ReflectionUtils.doWithMethods(cacheValue.getClass(), method -> {
                    ReflectionUtils.makeAccessible(method);
                    boolean cacheAnnotationPresent = method.isAnnotationPresent(Cacheable.class);
                    if(cacheAnnotationPresent){
                        Cacheable cacheable = method.getAnnotation(Cacheable.class);
                        for (String name : cacheable.cacheNames()) {
                            Caffeine caffeine = Caffeine.newBuilder().recordStats().initialCapacity(128).maximumSize(10240);
                            String[] nameExpire = name.split("#");
                            if (nameExpire.length > 1) {
                                caffeine.expireAfterWrite(Long.valueOf(nameExpire[1]), TimeUnit.SECONDS);
                            }
                            caffeineCacheManager.registerCustomCache(name, caffeine.build());
                        }
                        for (String name : cacheable.value()) {
                            Caffeine caffeine = Caffeine.newBuilder().recordStats().initialCapacity(128).maximumSize(10240);
                            String[] nameExpire = name.split("#");
                            if (nameExpire.length > 1) {
                                caffeine.expireAfterWrite(Long.valueOf(nameExpire[1]), TimeUnit.SECONDS);
                            }
                            caffeineCacheManager.registerCustomCache(name, caffeine.build());
                        }
                    }
                });
            }
        }
    }
}

 方法使用缓存

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

/**
 * LocalCacheService
 *
 * @Date: 2024-1-12 11:18
 * @Author: 
 * @Version: 1.0
 */
@Slf4j
@Component
public class LocalCacheService {

    @Cacheable(cacheNames = "currentTimeMillis#3", unless = "#result==null")
    public long currentTimeMillis(Integer a, String bb) {
        long start = System.currentTimeMillis();
        this.log.info("LocalCacheService--NoCache--currentTimeMillis()={}", start);
        return start;
    }

    @Cacheable(cacheNames = "currentTimeMillis#6", unless = "#result==null")
    public long currentTimeMillis2(Integer a, String bb) {
        long start = System.currentTimeMillis();
        this.log.info("LocalCacheService--NoCache--currentTimeMillis2()={}", start);
        return start;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值