@Configuration
public class HotKeyConfig {
@[Redacted Person]
public HotKeyDetector hotKeyDetector() {
// 配置热key探测器
return HotKeyDetector.builder()
.threshold(1000) // 热key阈值
.period(60) // 统计周期(秒)
.build();
}
}
缓存同步
[Redacted
@Service
public class CategoryService {
@CacheEvict(cacheNames = "category", allEntries = true)
@PostMapping("/refresh")
public void refreshCache() {
// 刷新所有分类缓存
// L2Cache 会自动通知其他节点同步刷新
}
}
五、监控与管理
缓存统计
[Redacted
@RestController
@RequestMapping("/cache")
public class CacheController {
@Autowired
private CacheService cacheService;
@GetMapping("/stats")
public CacheStats getCacheStats() {
// 获取缓存统计信息
return cacheService.getCacheStats();
}
}
手动管理缓存
[Redacted
@RestController
@RequestMapping("/cache")
public class CacheManagerController {
@DeleteMapping("/{cacheName}/{key}")
public void evictCache(@PathVariable String cacheName,
@PathVariable String key) {
// 手动清除指定缓存
cacheService.evict(cacheName, key);
}
@PostMapping("/{cacheName}/clear")
public void clearCache(@PathVariable String cacheName) {
// 清除某个缓存空间的所有数据
cacheService.clear(cacheName);
}
}
六、最佳实践建议
缓存命名规范
[Redacted
// 建议使用业务相关的有意义命名
public static final String CACHE_NAME_USER = "user";
public static final String CACHE_NAME_PRODUCT = "product";
public static final String CACHE_NAME_ORDER = "order";
// 缓存空值
public User getUser(Long id) {
User user = cacheService.get("user", String.valueOf(id));
if (user == CacheConstants.NULL_VALUE) {
return null;
}
if (user == null) {
user = userMapper.getById(id);
// 如果数据库也不存在,缓存空值
cacheService.put("user", String.valueOf(id),
user != null ? user : CacheConstants.NULL_VALUE);
}
return user;
}