Spring Boot应用中添加本地缓存 | 最新快讯

在Spring Boot应用中添加本地缓存是一种常见的优化手段,可以显著提升应用程序的响应时间和减少对后端数据源(如数据库)的压力。下面是一个使用Spring Boot添加本地缓存的基本步骤:

1. 添加依赖

首先,你需要在pom.xmlbuild.gradle中添加Spring Boot的缓存启动器依赖:

对于Maven:

Xml

1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-cache</artifactId>
4</dependency>

对于Gradle:

Groovy

implementation 'org.springframework.boot:spring-boot-starter-cache'

2. 开启缓存支持

在Spring Boot的主配置类上添加@EnableCaching注解以启用缓存支持。

Java


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yunjia.ntl.common.config.properties.CacheProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>初始化缓存管理器</p>
 *
 */
@Slf4j
@EnableCaching
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "cache.caffeine", value = "enabled")
public class CacheConfig {

    private final CacheProperties cacheProperties;

    /**
     * 创建基于Caffeine的Cache Manager
     */
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {

        log.debug("caffeine-plus create cacheManager");

        SimpleCacheManager cacheManager = new SimpleCacheManager();
        Map<String, CaffeineCache> cacheMap = new HashMap<>(2);

        // 设置全局配置的本地缓存
        List<String> globalCacheNames = cacheProperties.getCacheName();
        if (null != globalCacheNames && !globalCacheNames.isEmpty()) {
            addCacheObject(cacheMap, globalCacheNames, cacheProperties.getSpec());
        }

        // 设置自定义属性缓存, 可以覆盖全局缓存
        List<CacheProperties.Config> configs = cacheProperties.getConfigs();
        if (null != configs && !configs.isEmpty()) {
            for (CacheProperties.Config config : configs) {
                List<String> cacheNames = config.getCacheName();
                if (null == cacheNames || cacheNames.isEmpty()) {
                    continue;
                }
                addCacheObject(cacheMap, cacheNames, config.getSpec());
            }
        }
        // 加入到缓存管理器进行管理
        cacheManager.setCaches(cacheMap.values());

        return cacheManager;
    }

    /**
     * 添加缓存对象
     * 不支持refreshAfterWrite参数
     * refreshAfterWrite参数需要配合cacheLoader使用,需要自定义cacheManager
     */
    private void addCacheObject(Map<String, CaffeineCache> cacheMap, List<String> cacheNames, String caffeineSpec) {
        for (String cacheName : cacheNames) {

            /*
              初始化caffeine对象
             */
            Caffeine<Object, Object> caffeine = Caffeine.from(caffeineSpec).recordStats();

            /*
              监听缓存淘汰原因
             */
            caffeine.removalListener((key, value, cause) -> log.debug("缓存键 [{}], 缓存值 [{}] 被淘汰的原因为: [{}]", key, value, cause));

            /*
              构建caffeine缓存
             */
            Cache<Object, Object> cache = caffeine.build();
            CaffeineCache caffeineCache = new CaffeineCache(cacheName, cache);

            // 覆盖添加
            cacheMap.put(cacheName, caffeineCache);
        }

    }
}

或者在你的主应用类上添加此注解。

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>初始化缓存参数</p>
 */
@Data
@Component
@ConfigurationProperties(prefix = "cache.caffeine")
@ConditionalOnProperty(prefix = "cache.caffeine", value = "enabled")
public class CacheProperties {

    private List<String> cacheName;
    private String spec;

    private List<Config> configs;

    @Getter
    @Setter
    public static class Config {
        private List<String> cacheName;
        private String spec;
    }
}


import cn.hutool.extra.spring.SpringUtil;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>本地缓存工具类</p>
 */
@Slf4j
@SuppressWarnings("all")
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CacheUtil {

    private static final CacheManager CACHE_MANAGER = SpringUtil.getBean(CacheManager.class);

    /**
     * 缓存数据
     * 如果cacheName不存在,则抛异常
     * 如果key不存在,则创建新缓存
     * 如果key存在 在更新缓存
     *
     * @param cacheName 缓存名称
     * @param key       键
     * @param value     值
     */
    public static <T> void putCache(String cacheName, String key, T value) {
        getCache(cacheName).put(key, value);
    }

    /**
     * 提取缓存的值
     *
     * @param cacheName 缓存名称
     * @param key       键
     */
    public static <T> T getCacheValue(String cacheName, String key) {
        CaffeineCache caffeineCache = getCache(cacheName);
        if (null == caffeineCache.get(key)) {
            return null;
        }
        return (T) caffeineCache.get(key).get();
    }

    /**
     * 移除某个缓存
     *
     * @param cacheName 缓存名称
     * @param key       键
     */
    public static void delCache(String cacheName, Object key) {
        getCache(cacheName).evict(key);
    }

    /**
     * 清空缓存
     *
     * @param cacheName 缓存名称
     */
    public static void clearCaches(String cacheName) {
        getCache(cacheName).clear();
    }

    /**
     * 查询缓存清单
     */
    public static Collection<String> listCacheNames() {
        return CACHE_MANAGER.getCacheNames();
    }

    /**
     * 查询缓存性能参数
     */
    public static Map<String, CacheStats> listCachesStats() {
        Map<String, CacheStats> cacheStatses = new HashMap<>();

        Collection<String> cacheNames = listCacheNames();
        cacheNames.forEach(cacheName -> {
            com.github.benmanes.caffeine.cache.Cache<Object, Object> cache = getCache(cacheName).getNativeCache();
            CacheStats cacheStats = cache.stats();
            cacheStatses.put(cacheName, cacheStats);
        });

        return cacheStatses;
    }

    /**
     * 获取 CaffeineCache
     *
     * @param cacheName 缓存名称
     * @return CaffeineCache
     */
    public static CaffeineCache getCache(String cacheName) {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        if (null == cache) {
            return null;
        }
        return (CaffeineCache) cache;
    }
}

3. 使用缓存注解

在你想要缓存其结果的方法上使用@Cacheable注解。这个注解会告诉Spring在调用方法前检查缓存中是否已有结果,如果有的话,直接从缓存中获取,否则执行方法并将结果存储在缓存中。

Java

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable(value = "myCache")
    public String getData(String key) {
        // 耗时的操作,如查询数据库
        return "data for " + key;
    }
}

或者使用工具类

CacheUtil.putCache(CacheConstant.KEY_CACHE, CacheConstant.AUTH_KEY, accessToken);

public interface CacheConstant {

    /**
     * 密钥缓存
     */
    String KEY_CACHE = "keyCache";

    /**
     * 登录密钥
     */
    String AUTH_KEY = "auth:key";
}

4. 配置缓存管理器

你可以配置不同的缓存管理器,例如使用Caffeine。在application.propertiesapplication.yml中添加配置:

Properties

# 缓存配置
cache:
  caffeine:
    enabled: true
    # 全局配置
    cacheName: globalCache
    spec: maximumSize=10000,expireAfterWrite=1d
    # 自定义配置,cacheName相同可覆盖全局配置
    configs:
      - cacheName: keyCache
        spec: maximumSize=200,expireAfterWrite=30m

如果你想要更详细的配置,可以在@Configuration类中创建一个CaffeineCacheManager bean,并对其进行自定义配置。

Java

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 com.github.benmanes.caffeine.cache.Caffeine;

@Configuration
@EnableCaching
public class CaffeineCacheConfig {

    @Bean
    public CaffeineCacheManager caffeineCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(500)
                .expireAfterWrite(5, TimeUnit.MINUTES));
        return cacheManager;
    }
}

以上步骤将帮助你在Spring Boot应用中设置并使用本地缓存。确保根据你的具体需求调整缓存策略和配置。

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

www3300300

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值