spring缓存cache怎么用

发布时间:2021-10-27 15:41:30 作者:小新
来源:亿速云 阅读:136

这篇文章将为大家详细讲解有关spring缓存cache怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

spring缓存cache的使用

在spring配置文件中添加schema和spring对缓存注解的支持:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache.xsd"
       default-autowire="byName">
    <!--缓存配置-->
    <cache:annotation-driven/>

在spring配置文件中加入缓存管理器:

<!-- generic cache manager -->
    <bean id="cacheManager"
          class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                      p:name="hardwareCache"/>
                      <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" 
                      p:name="bannerCache"/>
            </set>
        </property>
    </bean>

然后在代码的service的impl层加上如下注解即可把数据缓存起来:

@Cacheable(value="bannerCache")

其中@Cacheable表示spring将缓存该方法获取到的数据,(缓存是基于key-value方式实现的),key为该方法的参数,value为返回的数据,当你连续访问该方法时你会发现只有第一次会访问数据库. 其他次数只是查询缓存.减轻了数据库的压力.

spring缓存cache怎么用

当更新了数据库的数据,需要让缓存失效时,使用下面的注解:

这个注解表示让appCache缓存的所有数据都失效。

@CacheEvict(value = "appCache", allEntries = true)

spring缓存cache怎么用

springcache配置缓存存活时间

Spring Cache @Cacheable本身不支持key expiration的设置,以下代码可自定义实现Spring Cache的expiration,针对Redis、SpringBoot2.0。

直接上代码:

@Service
@Configuration
public class CustomCacheMng{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    // 指明自定义cacheManager的bean name
    @Cacheable(value = "test",key = "'obj1'",cacheManager = "customCacheManager")
    public User cache1(){
        User user = new User().setId(1);
        logger.info("1");
        return user;
    }
    @Cacheable(value = "test",key = "'obj2'")
    public User cache2(){
        User user = new User().setId(1);
        logger.info("2");
        return user;
    }
    
    // 自定义的cacheManager,实现存活2天
    @Bean(name = "customCacheManager")
    public CacheManager cacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(2));
        return new RedisCacheManager(writer, config);
    }
    
    // 提供默认的cacheManager,应用于全局
    @Bean
    @Primary
    public CacheManager defaultCacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        return new RedisCacheManager(writer, config);
    }
}

关于“spring缓存cache怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. Spring- Cache缓存
  2. Spring Cache中怎么手动清理Redis缓存

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring cache

上一篇:Java如何实现获取wav时间长度

下一篇:Mysql数据分组排名实现的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》