CacheHealthIndicator.java 1.39 KB
package com.infoloop.tianting.cache;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;

/**
 * 缓存健康检查指示器
 */
@Slf4j
public class CacheHealthIndicator implements HealthIndicator {

    @Autowired
    @Qualifier("multiLevelCacheService")
    private CacheService cacheService;

    @Override
    public Health health() {
        try {
            // 执行简单的缓存操作来检查健康状态
            String testKey = "health_check_" + System.currentTimeMillis();
            cacheService.put(testKey, "test", 10);
            Object value = cacheService.get(testKey);
            cacheService.evict(testKey);

            if ("test".equals(value)) {
                return Health.up()
                    .withDetail("status", "缓存服务正常")
                    .build();
            } else {
                return Health.down()
                    .withDetail("status", "缓存读写异常")
                    .build();
            }
        } catch (Exception e) {
            return Health.down()
                .withDetail("status", "缓存服务异常")
                .withDetail("error", e.getMessage())
                .build();
        }
    }
}