@chcheable 配合 CaffeineCache 使用

引入依赖


        org.springframework.boot
            spring-boot-starter-cache
        

        
            com.github.ben-manes.caffeine
            caffeine
        

配置类

package com.mongodb.demo.cache;

import com.github.benmanes.caffeine.cache.Caffeine;
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.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: 
 * @description:
 * @create: 
 **/
@Configuration
@EnableCaching
public class CmsLocalCacheConfiguration {

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

        List caches = new ArrayList<>();
        for (Caches c : Caches.values()) {
            caches.add(new CaffeineCache(c.name(),
                    Caffeine.newBuilder()
                            .recordStats()
                            .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
                            .maximumSize(c.getMaxSize())
                            .build())
            );
        }
        cacheManager.setCaches(caches);
        return cacheManager;
    }

    public enum Caches {
        runoob(20 * 60, 1000),
        users(10 * 60, 3000);

        private int ttl;

        private int maxSize;

        Caches(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        public int getTtl() {
            return ttl;
        }

        public int getMaxSize() {
            return maxSize;
        }

    }
}

业务代码

@GetMapping("findAll")
    @Cacheable(value = "users")
    public Object query() {
        return mongoDbService.findAll();
    }

你可能感兴趣的:(@chcheable 配合 CaffeineCache 使用)