自学内容网 自学内容网

Springboot中的缓存使用

springboot 默认存储位置

默认缓存

 JVM 堆内存, 默认缓存大小 16M,但旨在单个应用实例内有效,且缓存的数据量不会太大。

redis

 缓存存储位置为 Redis, 分布式共享,多个应用实例可以共享缓存。

默认缓存使用步骤

1. 添加pom依赖

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>

2.在主应用类或配置类上添加 @EnableCaching 注解

@SpringBootApplication
@EnableCaching
public class SpringBootApiApplication {

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

    }

}

3.业务方法增加缓存注解 @Cacheable(value = “users”, key = “#name”),即开启缓存服务。

  @RequestMapping(value = "/users")
@Cacheable(value = "User", key = "#name")
public List<User> getUsers(String  name) {

    //创建用户集合
    List<User> users = new ArrayList<>();

    // 添加空值检查避免 NullPointerException
    if (name != null && !name.isEmpty()) {
        // 使用stream流过滤
        users = users.stream()
                .filter(user -> user.getName() != null && user.getName().contains(name))
                .toList();
    }

    return users;
 }

 PS: @Cacheable: 表示该方法的结果可以被缓存 value = "users": 指定缓存名称 key = "#name": 使用方法参数 name 作为缓存的键

4.修改删除业务方法需要清楚缓存使用注解 @CacheEvict(value = “users”, key = “#name”)

5.配置redis缓存

 * 前提条件 项目已集成redis
 * Spring Boot 应用启动时扫描到 CacheConfig 类
 * 检测到 @Configuration 注解,将其注册为配置类
 * 检测到 @EnableCaching 注解,启用缓存基础设施
 * 初始化 CacheManager Bean 并配置 Redis 连接
  @Configuration
  @EnableCaching
  public class CacheConfig {

       @Bean
       public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
           RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
               .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig())
              .build();
           return cacheManager;
       }
   }
   PS:
    *     //@Component 用于标注类,表示该类为Spring中的bean组件
    *     //@Bean 用于标注方法,表示这个方法返回的bean对象会被Spring管理,通常在配置类中使用,配合@Configuration注解

原文地址:https://blog.csdn.net/ChengR666/article/details/155710712

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