1. 首页
  2. 软件开发
  3. Spring——缓存的使用

Spring——缓存的使用

  • 发布于 2024-08-17
  • 0 次阅读

Spring框架提供了强大的缓存支持,可以帮助应用程序提高性能和响应速度。Spring的缓存支持包括注解驱动的缓存和基于接口的缓存管理。

Spring缓存支持:

  1. 使用步骤:

    • 在需要缓存的方法上添加 @Cacheable 注解来指定方法的返回值应该被缓存。
    • 使用 @CacheEvict 注解来指定方法调用时清除缓存。
    • 需要在配置类上添加 @EnableCaching 注解开启缓存支持。
  2. 代码如下:

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

@Service
public class CacheService {
   

    @Cacheable(value = "dataCache", key = "#id")
    public String getCachedDataById(Long id) {
   
        // 从数据库或其他数据源获取数据
        return "Data for id " + id;
    }

    @CacheEvict(value = "dataCache", key = "#id")
    public void evictCachedDataById(Long id) {
   
        // 清除缓存
    }
}
  1. 配置类:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {
   
    // 缓存配置
}

@Cacheable 注解用于标记方法 getCachedDataById ,指定了缓存的名称为"dataCache",并指定了缓存的key为方法的参数"id"。 @CacheEvict 注解用于标记方法 evictCachedDataById ,表示清除指定缓存。通过在配置类中添加 @EnableCaching 注解,开启了Spring的缓存支持。

原文链接: https://blog.csdn.net/2401_82884096/article/details/137932244