Spring Boot中自带缓存

106 阅读2分钟

在实际的应用中,缓存是提高系统性能的关键。Spring Boot通过集成Spring框架的缓存抽象,为我们提供了在应用中轻松使用缓存的方式。

1. 创建一个Spring Boot项目

首先,创建一个简单的Spring Boot项目。你可以使用Spring Initializr(start.spring.io/)进行快速初始化。

2. 启用缓存

在主应用程序类上添加 @EnableCaching 注解以启用缓存:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

3. 创建一个简单的服务类

创建一个简单的服务类 MyService,在该类的方法上添加缓存注解:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable(value = "myCache", key = "#input")
    public String performTask(String input) {
        System.out.println("执行耗时任务");
        return "任务结果:" + input;
    }
}

在这里,我们使用了 @Cacheable 注解来指定缓存的名称为 "myCache",并且使用输入参数作为缓存的键。

4. 编写主应用程序

编写主应用程序类 DemoApplication,调用 MyService 的方法:

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

@Component
public class MyRunner implements CommandLineRunner {

    private final MyService myService;

    public MyRunner(MyService myService) {
        this.myService = myService;
    }

    @Override
    public void run(String... args) {
        System.out.println(myService.performTask("input1"));
        System.out.println(myService.performTask("input2"));
        System.out.println(myService.performTask("input1")); // 从缓存中获取,不执行实际任务
    }
}

5. 运行应用程序

运行应用程序,你将看到如下输出:

arduinoCopy code
执行耗时任务
任务结果:input1
执行耗时任务
任务结果:input2
任务结果:input1   // 从缓存中获取,不执行实际任务

这里,我们通过使用 @Cacheable 注解,避免了对相同输入参数的重复计算,从而提高了性能。

Spring Boot提供了对多种缓存提供者的支持,包括EhCache、Redis、Caffeine等,你可以根据项目的需求选择适合的缓存实现。

希望这篇更深入的技术分享对你有所帮助。如果你有其他Spring Boot相关的主题或者其他技术方向的需求,欢迎告诉我。感谢阅读,我们下次再见!