引入依赖
<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.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<CaffeineCache> 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();
}