Spring Boot启动项目时如何加载缓存

在SpringBoot项目中,执行启动时的初始化工作(如加载缓存)是一个常见的需求。可以通过多种方式实现,包括使用@PostConstruct注解、实现ApplicationRunner或CommandLineRunner接口,以及监听Spring的生命周期事件。下面详细介绍这些方法,并给出相应的代码示例。

方法一:使用 @PostConstruct 注解

@PostConstruct注解可以用来标记一个方法,在依赖注入完成后立即执行。这个方法在Spring容器初始化完毕后自动调用,非常适合做一些初始化工作。

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class CacheLoader {

    @PostConstruct
    public void loadCache() {
        // 初始化缓存
        System.out.println("Loading cache at startup...");
        // 例如:缓存某些数据
    }
}

方法二:实现 CommandLineRunner 接口

实现CommandLineRunner接口的run方法,SpringBoot启动时会调用这个方法,适合用来执行启动时的初始化任务。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CacheLoader implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 初始化缓存
        System.out.println("Loading cache at startup...");
        // 例如:缓存某些数据
    }
}

方法三:实现 ApplicationRunner 接口

与CommandLineRunner类似,ApplicationRunner接口也是在SpringBoot启动完成后调用,但提供了更为丰富的ApplicationArguments对象,可以用于处理传入的命令行参数。

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class CacheLoader implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 初始化缓存
        System.out.println("Loading cache at startup...");
        // 例如:缓存某些数据
    }
}

方法四:监听 Spring 的生命周期事件

通过实现ApplicationListener接口或使用@EventListener注解,监听 ApplicationReadyEvent事件,在SpringBoot启动完成后执行初始化工作。

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class CacheLoader implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 初始化缓存
        System.out.println("Loading cache at startup...");
        // 例如:缓存某些数据
    }
}

或者使用 @EventListener 注解:

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class CacheLoader {
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        // 初始化缓存
        System.out.println("Loading cache at startup...");
        // 例如:缓存某些数据
    }
}

选择合适的方法
选择哪种方法取决于具体的需求和使用场景:

  • 如果初始化工作是一个Bean的属性,则推荐使用@PostConstruct注解。

  • 如果需要访问命令行参数,推荐使用ApplicationRunner或CommandLineRunner。

  • 如果需要监听应用上下文事件,推荐使用ApplicationListener或 @EventListener。

示例:加载缓存数据

假设我们要在应用启动时加载一些用户数据到缓存中,以下是一个完整的示例:
示例代码

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CacheLoader implements CommandLineRunner {
    private Map<Integer, String> userCache = new HashMap<>();
    @Override
    public void run(String... args) throws Exception {
        // 模拟从数据库加载用户数据到缓存
        userCache.put(1, "Alice");
        userCache.put(2, "Bob");
        userCache.put(3, "Charlie");
        System.out.println("User cache loaded at startup: " + userCache);
    }
    public String getUserById(int userId) {
        return userCache.get(userId);
    }
}

测试类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CacheLoaderApplication implements CommandLineRunner {
    @Autowired
    private CacheLoader cacheLoader;
    public static void main(String[] args) {
        SpringApplication.run(CacheLoaderApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        // 测试缓存数据
        System.out.println("User with ID 1: " + cacheLoader.getUserById(1));
        System.out.println("User with ID 2: " + cacheLoader.getUserById(2));
        System.out.println("User with ID 3: " + cacheLoader.getUserById(3));
    }
}

通过以上方式,可以确保在SpringBoot项目启动时执行必要的初始化工作,如加载缓存数据,从而提高应用的性能和响应速度。

明白了,你的需求是在程序启动自动将一些对象存入 Caffeine 缓存中,并且另一个服务可以随调用该缓存。以下是一个示例,演示了如何实现这个需求。 首先,确保你的项目中已经引入了 Caffeine 的依赖。 接下来,我们创建一个名为 `CacheInitializer` 的类,用于在程序启动初始化缓存并将对象存入其中: ```java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; public class CacheInitializer { private static Cache<String, Object> cache; public static void initializeCache() { // 创建缓存实例 cache = Caffeine.newBuilder() .maximumSize(100) // 设置缓存最大容量 .build(); // 将对象存入缓存 cache.put("key1", new Object()); cache.put("key2", new Object()); cache.put("key3", new Object()); // 其他初始化操作... } public static Cache<String, Object> getCache() { return cache; } } ``` 在上述代码中,我们使用了 Caffeine 的 `Caffeine.newBuilder()` 方法来创建缓存实例,并通过 `maximumSize()` 方法设置了最大容量为 100。你可以根据实际需求进行调整。然后,我们可以在 `initializeCache()` 方法中将需要存入缓存的对象使用 `put()` 方法添加到缓存中。 接下来,在你的应用程序的入口类中,你可以调用 `CacheInitializer.initializeCache()` 方法来初始化缓存,并且在需要访问缓存的地方,可以使用 `CacheInitializer.getCache()` 方法获取缓存实例。 ```java public class Main { public static void main(String[] args) { // 初始化缓存 CacheInitializer.initializeCache(); // 获取缓存实例 Cache<String, Object> cache = CacheInitializer.getCache(); // 在其他地方使用缓存 Object value = cache.getIfPresent("key1"); System.out.println(value); // 输出: 对象的值 } } ``` 在上述代码中,我们在程序启动调用了 `CacheInitializer.initializeCache()` 方法来初始化缓存,并且在需要访问缓存的地方,使用 `CacheInitializer.getCache()` 方法获取了缓存实例,并通过该实例调用 `getIfPresent()` 方法来获取缓存中的对象。 希望这个示例能满足你的需求!如果有任何问题,请随向我提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值