Springboot集成Caffeine

前言:

在系统中,有些数据,访问十分频繁,往往把这些数据放入分布式缓存中,但为了减少网络传输,加快响应速度,缓存分布式缓存读压力,会把这些数据缓存到本地JVM中,大多是先取本地缓存中,再取分布式缓存中的数据,Caffeine是一个高性能Java 缓存库,使用Java8对Guava缓存重写版本,在Spring Boot 2.0中将取代Guava

一、引入依赖

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

二、开启缓存

主启动类添加注解@EnableCaching

三、Controller层

@RestController
public class CacheController {
    @Autowired
    CacheService cacheService;

    @RequestMapping("cacheMethod01")
    public String cacheMethod01(String key) {
        return cacheService.cacheMethod01(key);
    }

    @RequestMapping("cacheMethod02")
    public String cacheMethod02(String key) {
        return cacheService.cacheMethod02(key);
    }

}

四、Service层

@Service
public class CacheService {
    @Cacheable(value = "cacheMethod01", key = "#key")
    public String cacheMethod01(String key) {
        System.out.println("cacheMethod01()方法执行,key="+key);
        return "cacheMethod01...,key="+key;
    }
    @Cacheable(value = "cacheMethod02", key = "#key")
    public String cacheMethod02(String key) {
        System.out.println("cacheMethod02()方法执行,key="+key);
        return "cacheMethod02...,key="+key;
    }

}

五、消亡时间枚举类

public enum CacheType {

    cacheMethod01(10),

    cacheMethod02(5);

    private int expires; // 消亡时间

    CacheType(int expires) {
        this.expires = expires;
    }

    public int getExpires() {
        return expires;
    }
}

六、配置类

@Configuration
public class CaffeineConfig {

    @Bean
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<CaffeineCache> caffeineCaches = new ArrayList<>();

        for (CacheType cacheType : CacheType.values()) {
            caffeineCaches.add(new CaffeineCache(cacheType.name(),
                    Caffeine.newBuilder()
                            .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
                            .build()));
        }

        cacheManager.setCaches(caffeineCaches);

        return cacheManager;
    }
}

七、配置文件(不推荐)

spring.cache.cache-names=cacheMethod01, cacheMethod02
spring.cache.caffeine.spec=initialCapacity=50,maximumSize=500,expireAfterWrite=5s
spring.cache.type=caffeine

你可能感兴趣的:(java,java)