添加热点缓存

This commit is contained in:
zk
2026-08-05 12:34:25 +08:00
parent 5074297775
commit d9239a2b68
3 changed files with 83 additions and 0 deletions
+9
View File
@@ -45,6 +45,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Spring Cache 抽象 + Caffeine 本地缓存,用于热门榜单等全局只读数据 -->
<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>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
@@ -0,0 +1,69 @@
package org.jiayunet.config;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
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;
/**
* 本地缓存配置
* <p>基于 Caffeine 的 Spring Cache 实现,用于热门榜单等全局只读、变化慢、允许短时陈旧的数据</p>
* <p>每个缓存独立注册、独立过期时间,调整某个缓存的时长直接改注册时传入的分钟数,互不影响</p>
*
* @author zk
*/
@Configuration
@EnableCaching
public class CacheConfig {
/** 缓存名:热门行业 */
public static final String HOT_INDUSTRY = "hotIndustry";
/** 缓存名:热门岗位类型 */
public static final String HOT_JOB_CATEGORY = "hotJobCategory";
/** 缓存名:热门城市 */
public static final String HOT_CITY = "hotCity";
/** 单个缓存最大条目数 */
private static final long MAX_SIZE = 100;
/**
* 缓存管理器
* <p>三个热门榜单各注册一份独立的 Caffeine 实例,过期时间互相独立(单位:分钟)</p>
* <p>另设一份兜底策略:业务里如果用了未登记的缓存名,动态创建时同样带过期时间,不会永不过期</p>
*/
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
// 兜底策略(动态创建未登记缓存时生效)
cacheManager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(MAX_SIZE));
// 各缓存独立注册,独立过期时间
cacheManager.registerCustomCache(HOT_INDUSTRY, buildCache(60));
cacheManager.registerCustomCache(HOT_JOB_CATEGORY, buildCache(60));
cacheManager.registerCustomCache(HOT_CITY, buildCache(60));
return cacheManager;
}
/**
* 构建一个指定过期时长的 Caffeine 缓存实例
*
* @param expireMinutes 写入后过期时长(分钟)
*/
private Cache<Object, Object> buildCache(long expireMinutes) {
return Caffeine.newBuilder()
.expireAfterWrite(expireMinutes, TimeUnit.MINUTES)
.maximumSize(MAX_SIZE)
.build();
}
}