Spring Boot 实现缓存预热的方法通常是在应用启动时执行一些操作来预加载缓存数据。这可以通过实现 CommandLineRunner 或 ApplicationRunner 接口来完成。
以下是一个使用 CommandLineRunner 接口的例子:
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
 
@SpringBootApplication
@EnableCaching
public class CacheWarmupApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(CacheWarmupApplication.class, args);
    }
 
    @Bean
    public CommandLineRunner run() {
        return args -> {
            // 在这里执行缓存数据的预加载操作
            // 例如,使用 CacheManager 或者 @Cacheable 注解的方法来加载缓存数据
        };
    }
}在 CommandLineRunner 的 run 方法中,你可以编写你的缓存预热逻辑。这段代码会在 Spring Boot 应用启动完成后自动执行。
如果你使用的是 Redis 作为缓存,并希望预热缓存,你可以预先将数据存入 Redis,例如:
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
 
@Bean
public CommandLineRunner run(StringRedisTemplate redisTemplate) {
    return args -> {
        // 预热缓存
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");
        // ... 更多键值对的设置
    };
}这样,在应用启动时,就会自动将指定的数据加载到缓存中。