自学内容网 自学内容网

Spring Cache 的说明及常用注解

一.介绍

     Spring Cache是Spring Framework中的一个模块,用于简化和统一缓存的使用。它提供了一种将缓存逻辑与应用程序业务逻辑分离的方式,使得我们可以更方便地使用缓存来提高应用程序的性能。

二.主要特性

  1. 注解支持:Spring Cache提供了一组注解(如@Cacheable@CachePut@CacheEvict),使得开发者可以通过简单的注解来定义缓存逻辑,而无需编写复杂的缓存管理代码。
  2. 多种缓存提供者支持:Spring Cache支持多种缓存实现,包括但不限于Ehcache、Caffeine、Redis、Hazelcast等。开发者可以根据需求选择合适的缓存提供者。
  3. 抽象层:Spring Cache提供了一个统一的抽象层,使得不同的缓存源可以在相同的API下工作,降低了锁定于某一特定缓存实现的风险。
  4. 灵活的配置:通过XML或Java配置,Spring Cache允许灵活地配置缓存属性,如过期时间、缓存名称等。

三.常用注解

1.@EnableCaching

  • 说明:启用缓存注解功能,通常加在启动类上。
  • 用途:使得 Spring 能够解析缓存注解并执行相关的缓存操作。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching  // 启用缓存
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.@Cacheable(常用于查询操作)

  • 说明:在方法上标记该方法的返回值可以缓存。
  • 用途:在方法执行前先查询缓存是否有数据。如果有,则直接返回缓存数据;如果没有,则执行方法并将返回值放入缓存中。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Cacheable("users")  // 指定缓存的名称
    public User getUserById(Long id) {
        // 假设从数据库查询用户
        return userRepository.findById(id);
    }
}

3.@CachePut(常用于更新操作)

  • 说明:更新缓存,直接将方法的返回值放入缓存中。
  • 用途:无论是否命中缓存,都会执行该方法,并将结果放入缓存中。
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @CachePut(value = "users", key = "#user.id")  // 通过用户ID作为缓存键
    public User updateUser(User user) {
        // 假设更新用户信息到数据库
        return userRepository.save(user);
    }
}

4.@CacheEvict

  • 说明:从缓存中移除一条或多条数据。
  • 用途:可以在更新或删除数据后,清理相关缓存以保持数据一致性。
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @CacheEvict(value = "users", key = "#id")  // 根据用户ID移除缓存
    public void deleteUser(Long id) {
        // 假设删除数据库中的用户
        userRepository.deleteById(id);
    }
}
通过这些注解的组合使用,能够有效提高系统的性能和响应速度,特别是在频繁读取数据的场景下。

原文地址:https://blog.csdn.net/qq_44858608/article/details/142747482

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!