本地缓存Caffeine实战

一.pom引入依赖

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

二.配置缓存管理器

package com.example.base.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.Data;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author 土
 * @version 1.0
 * @date 2024/6/21
 * @description
 */
@EnableCaching
@Configuration
@Data
public class SpringCacheConfig {
    @Bean
    public CaffeineCacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                // 设置过期时间,写入后5秒过期
                .expireAfterWrite(5, TimeUnit.SECONDS)
                // 初始化缓存空间大小
                .initialCapacity(100)
                // 最大的缓存条数
                .maximumSize(200)
        );
        return cacheManager;
    }
}

配置项说明

  • expireAfterAccess(long, TimeUnit):设置缓存项在指定的时间段内没有被读/写访问后将被移除。
  • expireAfterWrite(long, TimeUnit):设置缓存项在指定的时间段内没有被写入访问后将被移除。

注意:Caffeine缓存库内部默认使用的是近似的LRU(Least Recently Used,最近最少使用)策略,这是一种基于访问频率和访问时间的淘汰策略。当缓存达到最大容量时,最近最少使用的缓存项将被移除。

三.使用缓存注解

注意:@CacheEvict要一定保持和缓存的键值一致

@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {
    public String get(String str) {
        log.info("get-str:{},现在是:{}", str, LocalDateTime.now());
        return str;
    }

    /**
     * 使用缓存
     *
     * @param str
     * @return
     */
    @Cacheable(value = "user", key = "#str", unless = "#result == null")
    @Override
    public String getByCache(String str) {
        return get(str);
    }

    /**
     * 清除缓存
     *
     * @param str
     */
    @CacheEvict(value = "user", key = "#str")
    public void clearCache(String str) {
        log.info("清除缓存:{}", str);
    }
}

四.controller验证

    @GetMapping(value = "getUser", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getUser(String str) {
        log.info("接口请求的str:{}", str);
        return userInfoService.getByCache(str);
    }

3次请求。根据控制台输出可以看出缓存生效,并且配置的expireAfterWrite配置项也生效:超过5秒则缓存失效

在这里插入图片描述

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值