SpringMVC使用缓存

文章展示了如何在SpringMVC环境中配置并使用缓存,包括启用缓存注解,创建CacheManager,定义缓存实例和键生成策略。在测试类中,通过@Cacheable注解实现方法的缓存,并遇到对实体类(User)转换的问题,解决方案是引入Jackson库进行JSON格式转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现步骤

  1. 新建 SpringConfig.class 作为 springMVC 的配置类,要注入 CacheManager,否则注解无法使用
@Configuration
@EnableWebMvc
@EnableCaching // 打开缓存驱动
@ComponentScan(basePackages = "com.ibm.redis")
public class SpringConfig extends WebMvcConfigurationSupport {
    // 定义 CacheManager,该方法必需
    @
Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("myCache")));
        /*cacheManager.setCaches(Arrays.asList (
            // 新建2个缓存实例
            new ConcurrentMapCache[] {
                new ConcurrentMapCache("default"),
                new ConcurrentMapCache("test"),
                new ConcurrentMapCache("users")}));*/
        return cacheManager;
    }

    // 定义 key 的生成策略,该方法非必需
    @Bean
    public KeyGenerator keyGenerator() {
        return new MyKeyGenerator();
    }
}

注意

  1. cacheManager 方法中可以添加多个缓存实例,缓存实例将会在后面用到

  2. MyKeyGenerator 类的实现

// 缓存键的生成策略
public class MyKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object ... params) {
        return target.getClass().getName() + method.getName();
    }
}
  1. 新建 RedisServer.class 用于测试
@Service
public class RedisServer {
    @Cacheable(cacheNames = "myCache", key = "targetClass")
    public String get1() {
        System.out.println(new Date() + "--> No value from cache");
        return "Ramos";
    }

    @Cacheable(cacheNames = "myCache", key = "targetClass")
    public User get2() {
        System.out.println(new Date() + "--> No value from cache");
        return new User(1, "dufu");
    }
}

注意:@Cacheable 标签中的 cacheNames 属性的值 myCache 就是我们在 SpringConfig.class 中添加的缓存实例的属性值,一定要对应上,否则会报错

  1. 当然对于一个类中,如果 @Cacheable 标签中的 cacheNames 属性一致的话,我们同样可以使用@CacheConfig 来减少代码量,修改后的 RedisServer.class 如下
@Service
@CacheConfig(cacheNames = "myCache", keyGenerator = "keyGenerator")
public class RedisServer {
    @Resource
    private CacheManager cacheManager;
   
    @Cacheable
    public String get1() {
        System.out.println(new Date() + "--> No value from cache");
        return "Ramos";
    }
    
    @Cacheable
    public User get2() {
        System.out.println(new Date() + "--> No value from cache");
        return new User(1, "dufu");
    }
}
  1. 当我们在测试的时候发现,调用 get2() 方法的时候会报错,提示对于 User.class 没有转换器
    在这里插入图片描述
    当出现这种情况我们应该提供一个 JSON 格式的转换来处理实体类,解决方法也十分简单,只需要在 pom.xml 中添加 jackson 的依赖即可
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.7</version>
</dependency>
<think>嗯,用户想在Spring MVC中设置和使用全局缓存机制。首先,我需要回忆一下Spring MVC中关于缓存的组件和配置方法。记得Spring框架本身提供了一些缓存支持,比如通过@Cacheable注解,但可能需要结合其他缓存库,比如Ehcache或者Redis。 用户提到的全局缓存,应该是指应用级别的缓存,所有用户都能共享的那种。首先,可能需要配置一个CacheManager,这是Spring缓存抽象的核心。然后,在配置类里启用缓存,比如使用@EnableCaching注解。接下来,具体的缓存配置,比如使用Ehcache的话,需要ehcache.xml文件定义缓存策略,或者通过Java配置。 另外,用户之前的问题中引用了MyBatis的一级和二级缓存,但这里用户问的是Spring MVC的全局缓存,可能需要区分开。Spring的缓存机制更偏向于业务层,而不是数据访问层。所以应该考虑在Service层使用缓存注解。 步骤可能包括:添加依赖,比如Spring Boot的starter-cache,以及具体的缓存实现库,比如Ehcache或Redis。然后配置CacheManager,定义缓存名称和策略。接着在需要缓存的方法上添加@Cacheable注解。此外,可能还需要配置WebMvcConfigurer来设置静态资源的缓存策略,比如通过资源处理器设置缓存时间。 还要注意是否需要处理静态资源的缓存,比如引用[2]中提到的使用<mvc:default-servlet-handler/>,这可能影响静态资源的处理,但用户的问题更偏向于应用数据的全局缓存,所以重点应该在业务层缓存的配置。 可能还需要考虑缓存的一致性,比如使用@CacheEvict在数据更新时清除缓存。另外,全局缓存可能需要分布式缓存方案,比如Redis,特别是当应用部署在多个实例上时,这样可以保证所有实例共享同一缓存数据。 总结一下,步骤大概是:添加依赖、配置CacheManager、启用缓存注解、在Service方法中使用缓存注解、可能配置静态资源缓存。需要确保配置正确,并且根据实际需求选择本地缓存或分布式缓存。</think>### Spring MVC全局缓存配置步骤及示例 #### 1. 添加依赖与启用缓存 在`pom.xml`中添加Spring Cache和缓存实现(以Ehcache为例): ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 通过`@EnableCaching`启用缓存: ```java @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { return new EhCacheCacheManager(ehCacheManager()); } @Bean public EhCacheManagerFactoryBean ehCacheManager() { EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean(); factory.setConfigLocation(new ClassPathResource("ehcache.xml")); return factory; } } ``` #### 2. 定义缓存策略(ehcache.xml) ```xml <ehcache> <cache name="globalCache" maxEntriesLocalHeap="1000" timeToLiveSeconds="3600"/> </ehcache> ``` #### 3. 在Service层使用缓存 通过`@Cacheable`标注需缓存的方法: ```java @Service public class UserService { @Cacheable(value = "globalCache", key = "#userId") public User getUserById(String userId) { // 数据库查询逻辑 } @CacheEvict(value = "globalCache", key = "#userId") public void updateUser(User user) { // 更新逻辑 } } ``` #### 4. 静态资源缓存配置(可选) 通过`WebMvcConfigurer`配置静态资源缓存策略[^2]: ```java @Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/") .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS)); } } ``` #### 5. 分布式缓存扩展(Redis示例) ```java @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1)); return RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值