SpringBoot缓存注解使用

简介: Spring Boot 提供了一套方便的缓存注解,用于简化缓存管理。通过 `@Cacheable`、`@CachePut`、`@CacheEvict` 和 `@Caching` 等注解,开发者可以轻松地实现方法级别的缓存操作,从而提升应用的性能和响应速度。合理使用这些注解可以大大减少数据库的访问频率,优化系统性能。

Spring Boot 缓存注解使用

Spring Boot 提供了一套强大的缓存注解机制,用于简化和优化应用程序的缓存管理。通过缓存机制,开发者可以显著提升应用的性能,减少数据库访问频率。本文将详细介绍 Spring Boot 缓存注解的使用方法,包括配置、常用注解及其用法。

一、缓存配置

在 Spring Boot 中使用缓存,首先需要进行缓存配置。可以通过配置类或配置文件来启用缓存支持。

1. 添加依赖

pom.xml 文件中添加缓存依赖。这里以使用 EhCache 为例:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
AI 代码解读

2. 启用缓存支持

在 Spring Boot 应用的主类上添加 @EnableCaching 注解:

@SpringBootApplication
@EnableCaching
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}
​
AI 代码解读

3. 配置缓存管理器

可以在配置类中配置缓存管理器:

@Configuration
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
        factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factory.setShared(true);
        return factory;
    }
}
​
AI 代码解读

二、常用缓存注解

Spring 提供了一些常用的缓存注解,用于在方法级别进行缓存操作。

1. @Cacheable

@Cacheable 注解用于标记方法的返回值可以被缓存。每次调用该方法时,都会先检查缓存是否存在,如果存在则直接返回缓存结果,否则执行方法并将结果缓存。

@Cacheable(value = "users", key = "#userId")
public User getUserById(Long userId) {
    return userRepository.findById(userId).orElse(null);
}
​
AI 代码解读

2. @CachePut

@CachePut 注解用于更新缓存。每次调用该方法时,都会执行方法并将结果缓存。

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    userRepository.save(user);
    return user;
}
​
AI 代码解读

3. @CacheEvict

@CacheEvict 注解用于移除缓存。可以指定 allEntries 属性来清空整个缓存。

@CacheEvict(value = "users", key = "#userId")
public void deleteUser(Long userId) {
    userRepository.deleteById(userId);
}

@CacheEvict(value = "users", allEntries = true)
public void clearCache() {
    // 清空缓存
}
​
AI 代码解读

4. @Caching

@Caching 注解用于组合多个缓存操作注解。

@Caching(
    put = { @CachePut(value = "users", key = "#user.id") },
    evict = { @CacheEvict(value = "users", key = "#user.id") }
)
public User saveUser(User user) {
    userRepository.save(user);
    return user;
}
​
AI 代码解读

三、缓存示例

以下是一个完整的示例,展示了如何在 Spring Boot 应用中使用缓存注解。

1. 配置文件

src/main/resources 目录下创建 ehcache.xml 配置文件:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <cache name="users"
           maxEntriesLocalHeap="1000"
           timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LRU">
    </cache>

</ehcache>
AI 代码解读

2. 服务类

创建用户服务类,使用缓存注解:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Cacheable(value = "users", key = "#userId")
    public User getUserById(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    @CachePut(value = "users", key = "#user.id")
    public User updateUser(User user) {
        userRepository.save(user);
        return user;
    }

    @CacheEvict(value = "users", key = "#userId")
    public void deleteUser(Long userId) {
        userRepository.deleteById(userId);
    }

    @CacheEvict(value = "users", allEntries = true)
    public void clearCache() {
        // 清空缓存
    }
}
​
AI 代码解读

思维导图

Spring Boot 缓存注解使用

缓存配置

添加依赖

启用缓存支持

配置缓存管理器

常用缓存注解

@Cacheable

@CachePut

@CacheEvict

@Caching

缓存示例

配置文件

服务类

总结

Spring Boot 提供了一套方便的缓存注解,用于简化缓存管理。通过 @Cacheable@CachePut@CacheEvict@Caching 等注解,开发者可以轻松地实现方法级别的缓存操作,从而提升应用的性能和响应速度。合理使用这些注解可以大大减少数据库的访问频率,优化系统性能。

目录
相关文章
SpringBoot入门(8) - 开发中还有哪些常用注解
SpringBoot入门(8) - 开发中还有哪些常用注解
73 0
|
16天前
|
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
104 26
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
183 73
|
7天前
|
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
34 16
【SpringFramework】Spring IoC-基于注解的实现
本文主要记录基于Spring注解实现IoC容器和DI相关知识。
62 21
【Spring】获取Bean对象需要哪些注解
@Conntroller,@Service,@Repository,@Component,@Configuration,关于Bean对象的五个常用注解
【Spring配置】idea编码格式导致注解汉字无法保存
问题一:对于同一个项目,我们在使用idea的过程中,使用汉字注解完后,再打开该项目,汉字变成乱码问题二:本来a项目中,汉字注解调试好了,没有乱码了,但是创建出来的新的项目,写的注解又成乱码了。
Spring MVC核心:深入理解@RequestMapping注解
在Spring MVC框架中,`@RequestMapping`注解是实现请求映射的核心,它将HTTP请求映射到控制器的处理方法上。本文将深入探讨`@RequestMapping`注解的各个方面,包括其注解的使用方法、如何与Spring MVC的其他组件协同工作,以及在实际开发中的应用案例。
67 4
Spring MVC中的请求映射:@RequestMapping注解深度解析
在Spring MVC框架中,`@RequestMapping`注解是实现请求映射的关键,它将HTTP请求映射到相应的处理器方法上。本文将深入探讨`@RequestMapping`注解的工作原理、使用方法以及最佳实践,为开发者提供一份详尽的技术干货。
234 2
探索Spring MVC:@Controller注解的全面解析
在Spring MVC框架中,`@Controller`注解是构建Web应用程序的基石之一。它不仅简化了控制器的定义,还提供了一种优雅的方式来处理HTTP请求。本文将全面解析`@Controller`注解,包括其定义、用法、以及在Spring MVC中的作用。
84 2
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等