卡飞资源网

专业编程技术资源共享平台

Spring Boot中如何使用缓存?超简单

Spring Boot 中的缓存可以减少从数据库重复获取数据或执行昂贵计算的需要,从而显著提高应用程序的性能。Spring Boot 提供了与各种缓存提供程序的集成,您可以在应用程序中轻松配置和使用缓存。以下是有关如何在 Spring Boot 中使用缓存的分步指南:

1. 添加依赖项:
打开 pom.xml(对于 Maven)或 build.gradle(对于 Gradle)文件,并为您选择的缓存提供程序添加必要的依赖项。Spring Boot支持多种缓存提供程序,例如Ehcache、Caffeine、Redis等。例如,如果要使用Ehcache,请添加以下依赖项:

<! - For Maven →>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-cache</artifactId>
 </dependency>
 <dependency>
 <groupId>org.ehcache</groupId>
 <artifactId>ehcache</artifactId>
 </dependency>

请记住根据您选择的缓存提供程序修改依赖项。

2.启用缓存:

在您的Spring Boot主类带有@SpringBootApplication注解的类)中,添加@EnableCaching注解。该注释启用了 Spring 的缓存基础设施。

import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
 @EnableCaching
 public class YourApplication {
 public static void main(String[] args) {
 SpringApplication.run(YourApplication.class, args);
 }
 }

3. 配置缓存管理器:
Spring Boot 根据缓存提供程序的可用性自动配置默认缓存管理器。但是,您可以通过在配置中创建 CacheManager bean 来自定义缓存管理器。例如配置Ehcache:

import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.cache.CacheManager;
 import org.springframework.cache.ehcache.EhCacheCacheManager;
 import org.springframework.cache.annotation.EnableCaching;
@Configuration
 @EnableCaching
 public class CacheConfig {
 @Bean
 public CacheManager cacheManager() {
 return new EhCacheCacheManager(ehCacheManager());
 }
// 在这里定义你的 Ehcache 管理器 bean 
 @Bean
 public EhCacheManager ehCacheManager() {
 return new EhCacheManager();
 }
 }

4. 使用缓存:

请使用@Cacheable、@CachePut和@CacheEvict
等缓存注释来注释它们。

- @Cacheable:该注解表示该注解方法的结果应该被缓存。如果使用相同的参数再次调用该方法,将返回缓存的结果而不是执行该方法。

- @CachePut:该注解使用方法执行的结果更新缓存,无论数据是否已经缓存。

- @CacheEvict:此注释从缓存中删除数据。用它来指示在方法执行后应逐出缓存的数据。

这是使用@Cacheable的示例:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MyService {
 @Cacheable("myCache")
 public String getCachedData(String key) {
 // 方法实现
 return someData;
 }
}
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言