一.pom引入依赖
<!-- 缓存 -->
<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.example.base.config;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.Data;
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 java.util.concurrent.TimeUnit;
/**
* @author 土
* @version 1.0
* @date 2024/6/21
* @description
*/
@EnableCaching
@Configuration
@Data
public class SpringCacheConfig {
@Bean
public CaffeineCacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
// 设置过期时间,写入后5秒过期
.expireAfterWrite(5, TimeUnit.SECONDS)
// 初始化缓存空间大小
.initialCapacity(100)
// 最大的缓存条数
.maximumSize(200)
);
return cacheManager;
}
}
配置项说明
- expireAfterAccess(long, TimeUnit):设置缓存项在指定的时间段内没有被读/写访问后将被移除。
- expireAfterWrite(long, TimeUnit):设置缓存项在指定的时间段内没有被写入访问后将被移除。
注意:Caffeine缓存库内部默认使用的是近似的LRU(Least Recently Used,最近最少使用)策略,这是一种基于访问频率和访问时间的淘汰策略。当缓存达到最大容量时,最近最少使用的缓存项将被移除。
三.使用缓存注解
注意:@CacheEvict要一定保持和缓存的键值一致
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {
public String get(String str) {
log.info("get-str:{},现在是:{}", str, LocalDateTime.now());
return str;
}
/**
* 使用缓存
*
* @param str
* @return
*/
@Cacheable(value = "user", key = "#str", unless = "#result == null")
@Override
public String getByCache(String str) {
return get(str);
}
/**
* 清除缓存
*
* @param str
*/
@CacheEvict(value = "user", key = "#str")
public void clearCache(String str) {
log.info("清除缓存:{}", str);
}
}
四.controller验证
@GetMapping(value = "getUser", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(String str) {
log.info("接口请求的str:{}", str);
return userInfoService.getByCache(str);
}
3次请求。根据控制台输出可以看出缓存生效,并且配置的expireAfterWrite配置项也生效:超过5秒则缓存失效