Spring Boot 整合 Caffeine

一、添加依赖

        
            org.springframework.boot
            spring-boot-starter-cache
        
        
            com.github.ben-manes.caffeine
            caffeine
        

二、启动类上添加注解:

@org.springframework.cache.annotation.EnableCaching

三、配置

1、采用spring自带配置

############# 缓存配置 不推荐  建议自定义 #############
spring.cache.cache-names=USER,ADVERT
spring.cache.caffeine.spec=initialCapacity=50,maximumSize=500,expireAfterWrite=30s,refreshAfterWrite=7s
spring.cache.type=caffeine

2、自定义配置



/**
 * @author songjianyong
 * 

缓存名分类

*/ public enum CacheNameEnum { /** * 用户 */ USER(5, 20L, 60L), /** * 推荐 */ ADVERT(5, 10L, 120L); private final Integer initialCapacity; private final Long maximumSize; private final Long expire; CacheNameEnum(Integer initialCapacity, Long maximumSize, Long expire) { this.initialCapacity = initialCapacity; this.maximumSize = maximumSize; this.expire = expire; } public Long getMaximumSize() { return maximumSize; } public Integer getInitialCapacity() { return initialCapacity; } public Long getExpire() { return expire; } }

import com.coocaa.system.enums.CacheNameEnum;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
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 java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author songjianyong
 * 

本地缓存配置

*/ @Configuration public class CaffeineCacheConfig { private static final SimpleCacheManager SIMPLE_CACHE_MANAGER = new SimpleCacheManager(); @Bean public CacheManager caffeineCacheManager() { List caches = new ArrayList<>(); for (CacheNameEnum value : CacheNameEnum.values()) { com.github.benmanes.caffeine.cache.Cache cache = Caffeine.newBuilder() .initialCapacity(value.getInitialCapacity()) .maximumSize(value.getMaximumSize()) //写入后失效时间 .expireAfterWrite(Duration.ofSeconds(value.getExpire())) .build(); caches.add(new CaffeineCache(value.name(), cache)); } SIMPLE_CACHE_MANAGER.setCaches(caches); return SIMPLE_CACHE_MANAGER; } }

四、使用注解

@org.springframework.cache.annotation.Cacheable(value = "USER", key="#p0.id")

五、进阶处理

自定义 CaffeineCacheManager

import com.coocaa.ops.admin.common.enums.CacheNameEnum;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

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

/**
 * 自定义 CaffeineCacheManager
 *
 * @author songjianyong
 */
@Configuration
public class SongCaffeineCacheManager extends CaffeineCacheManager implements InitializingBean {
    private final Map> builders = new HashMap<>();
    @Nullable
    private CacheLoader cacheLoader;

    @Override
    public void afterPropertiesSet() throws Exception {
        for (CacheNameEnum value : CacheNameEnum.values()) {
            builders.put(value.getCacheName(), Caffeine.from(value.getSpec()));
        }
    }

    @Override
    @NonNull
    protected Cache createNativeCaffeineCache(@NonNull String name) {
        Caffeine builder = builders.get(name);
        if (builder == null) {
            return super.createNativeCaffeineCache(name);
        }

        if (this.cacheLoader != null) {
            return builder.build(this.cacheLoader);
        } else {
            return builder.build();
        }
    }

    @Override
    public void setCacheLoader(@NonNull CacheLoader cacheLoader) {
        super.setCacheLoader(cacheLoader);
        this.cacheLoader = cacheLoader;
    }
}

辅助代码

/**
 * 缓存名称枚举
 *
 * @author songjianyong
 */
public enum CacheNameEnum {
    /**
     * 接口响应结果缓存名称
     */
    SONG_API_RESPONSE("SONG:API:RESPONSE", "initialCapacity=5,maximumSize=50,expireAfterWrite=1d"),
    JIAN_API_RESPONSE("JIAN:API:RESPONSE", "initialCapacity=10,maximumSize=100,expireAfterWrite=15d");

    /**
     * 缓存名称
     */
    private final String cacheName;
    /**
     * spec
     */
    private final String spec;

    CacheNameEnum(String cacheName, String spec) {
        this.cacheName = cacheName;
        this.spec = spec;
    }

    public String getCacheName() {
        return cacheName;
    }

    public String getSpec() {
        return spec;
    }
}

你可能感兴趣的:(spring,Java,spring,boot,Caffeine)