package com.bonus.material.config; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.cache.interceptor.KeyGenerator; import java.lang.reflect.Method; import java.util.Arrays; /** * 缓存配置类 * 为getUseTypeTree方法优化提供缓存支持 */ @Configuration @EnableCaching public class CacheConfig { /** * 缓存管理器配置 * 使用ConcurrentMapCacheManager作为简单的内存缓存 * 生产环境建议使用Redis等分布式缓存 */ @Bean public CacheManager cacheManager() { ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); // 配置缓存名称 cacheManager.setCacheNames(Arrays.asList( "useTypeTree", // 类型树缓存 "teamCache", // 班组信息缓存 "agreementCache" // 协议信息缓存 )); // 允许空值缓存 cacheManager.setAllowNullValues(false); return cacheManager; } /** * 自定义键生成器 * 用于生成更精确的缓存键 */ @Bean("customKeyGenerator") public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getSimpleName()).append("."); sb.append(method.getName()).append("("); for (int i = 0; i < params.length; i++) { if (i > 0) { sb.append(","); } if (params[i] != null) { sb.append(params[i].toString()); } else { sb.append("null"); } } sb.append(")"); return sb.toString(); } }; } } /** * Redis缓存配置(可选) * 如果需要使用Redis作为缓存,可以启用以下配置 */ /* @Configuration @EnableCaching @ConditionalOnProperty(name = "spring.cache.type", havingValue = "redis") public class RedisCacheConfig { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(30)) // 缓存30分钟过期 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) .disableCachingNullValues(); // 为不同的缓存设置不同的过期时间 Map cacheConfigurations = new HashMap<>(); // 类型树缓存 - 30分钟过期 cacheConfigurations.put("useTypeTree", config.entryTtl(Duration.ofMinutes(30))); // 班组缓存 - 1小时过期 cacheConfigurations.put("teamCache", config.entryTtl(Duration.ofHours(1))); // 协议缓存 - 15分钟过期 cacheConfigurations.put("agreementCache", config.entryTtl(Duration.ofMinutes(15))); return RedisCacheManager.builder(connectionFactory) .cacheDefaults(config) .withInitialCacheConfigurations(cacheConfigurations) .build(); } } */