广告
返回顶部
首页 > 资讯 > 精选 >如何解决springCache配置中的坑
  • 525
分享到

如何解决springCache配置中的坑

2023-06-22 05:06:46 525人浏览 安东尼
摘要

本篇内容介绍了“如何解决springCache配置中的坑”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!sprinGCache配置中踩的坑项目

本篇内容介绍了“如何解决springCache配置中的坑”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

sprinGCache配置中踩的坑

项目基于SpringBoot,使用了SpringCache。

早先在网上找了一份SpringCache的配置,后来由于需要使用到自定义序列化方法,注入一个自定义的序列化类。但是在后来发现自定义的序列化类始终没有调用,后来查看源码后终于发现了原因

先附上正确的配置

  @Bean    public CacheManager cacheManager(RedisConnectionFactory factory, SessionSerializer serializer) {        logger.debug("生成缓存管理器");        logger.debug("注入的序列化工具={}", serializer);        RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer(serializer);        logger.debug("生成的cache序列化工具={}", pair);        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  // 生成一个默认配置,通过config对象即可对缓存进行自定义配置        config = config.entryTtl(Duration.ofMinutes(10))     // 设置缓存的默认过期时间,也是使用Duration设置                .serializeValuesWith(pair)//                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))                .disableCachingNullValues()        ;     // 不缓存空值        logger.debug("初始化完成的config={}", config);        // 设置一个初始化的缓存空间set集合        Set<String> cacheNames = new HashSet<>();        cacheNames.add(CACHE_NAME);        return RedisCacheManager.builder(new CusTtlRedisCacheWriter(factory))     // 使用自定义的缓存配置初始化一个cacheManager                .cacheDefaults(config)//这一句必须要最先执行,否则实际运行时使用的是defaultConfig                .initialCacheNames(cacheNames)//                .withInitialCacheConfigurations(configMap)//                .transactionAware()                .build();    }

重要在于最后一行return的时候,早先的找到的资料说initialCacheNames方法一定要先执行,否则就会巴拉巴拉~~~,,结果就掉坑了

如果initialCacheNames方法先执行的话,实际上CacheManager里使用的是DefaultConfig,里面的序列化方式也就是jdk序列化,后面在调用cacheDefaults也没有用了。

所有,cacheDetaults方法一定要先执行

springCache配置及一些问题的解决

配置

applicationContext.xml

<beans xmlns="Http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:cache="http://www.springframework.org/schema/cache"   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">      <cache:annotation-driven />  <!-- 定义缓存管理 -->    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">        <property name="caches">            <set>                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"                      p:name="default"/>                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"                      p:name="activityCache"/>                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"                      p:name="awardsCache"/>            </set>        </property>    </bean>

Spring内部默认使用 ConcurrentHashMap 来存储, 配置中的 activityCache awardsCache 就是一个一个的 ConcurrentHashMap 对象的名字. 另外 spring还支持使用 EHCache 来存储缓存.

在service的实现类上加上 @Cacheable

//@Service//public class LotteryActivityServiceImpl implements LotteryActivityService@Cacheable(value = "activityCache", key = "#shortName")public LotteryActivity findByShortName(String shortName) {    log.info("query activity : {} from database.", shortName);    return activityRepository.findByShortName(shortName);}

@Cacheable参数

value缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如: @Cacheable(value=”testcache”,key=”#userName”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 例如: @Cacheable(value=”testcache”,condition=”#userName.length()>2”)

在需要清除缓存的方法上加上@CacheEvict

@CacheEvict(value="activityCache", allEntries = true, beforeInvocation = true)public void cleanActivityCache(String shortName) {    log.info("cleaned cache activity : {}", shortName);}

@CacheEvict 参数

value缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @CachEvict(value=”mycache”) 或者 @CachEvict(value={”cache1”,”cache2”}
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如: @CachEvict(value=”testcache”,key=”#userName”
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才清空缓存 例如: @CachEvict(value=”testcache”, condition=”#userName.length()>2”)
allEntries是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存 例如: @CachEvict(value=”testcache”,allEntries=true)
beforeInvocation是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存 例如: @CachEvict(value=”testcache”,beforeInvocation=true)

当需要保证方法被调用,又希望结果被缓存, 可以使用@CachePut

@CachePut(value="accountCache",key="#account.getName()")// 更新 accountCache 缓存 public Account updateAccount(Account account) {    return updateDB(account);  }

@CachePut 参数

value缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如: @Cacheable(value=”testcache”,key=”#userName”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 例如: @Cacheable(value=”testcache”,condition=”#userName.length()>2”)

注解最好加在实现类而不是接口的方法上

Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Cache* annotation, as opposed to annotating interfaces. You certainly can place the @Cache* annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the caching settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a caching proxy, which would be decidedly bad.

带有@Cache* 注解的方法不能被定义在调用该方法的类里, 比如 UserController要调用 findUserByName(String name), 且该方法有 @Cacheabele注解, 那么该方法就不能被定义在 UserController中

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with @Cacheable - considering using the aspectj mode in this case.

@Cache*注解要加在 public 方法上

When using proxies, you should apply the @Cache* annotations only to methods with public visibility. If you do annotate protected, private or package-visible methods with these annotations, no error is raised, but the annotated method does not exhibit the configured caching settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods as it changes the bytecode itself.

“如何解决springCache配置中的坑”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!

--结束END--

本文标题: 如何解决springCache配置中的坑

本文链接: https://www.lsjlt.com/news/302571.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何解决springCache配置中的坑
    本篇内容介绍了“如何解决springCache配置中的坑”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!springCache配置中踩的坑项目...
    99+
    2023-06-22
  • 解决springCache配置中踩的坑
    目录springCache配置中踩的坑先附上正确的配置springCache配置及一些问题的解决配置@Cacheable参数@CacheEvict 参数@CachePut 参数spr...
    99+
    2022-11-12
  • mybatis配置mapper-locations的坑及解决
    目录mybatis配置mapper-locations的坑mapperLocations配置失效问题根源解决mybatis配置mapper-locations的坑 很多时候想把xml...
    99+
    2022-11-13
  • 解决SpringBoot加载application.properties配置文件的坑
    SpringBoot加载application.properties配置文件的坑 事情的起因是这样的 一次,本人在现场升级程序,升级完成后进行测试,结果接口调用都报了这么个错误: ...
    99+
    2022-11-12
  • 解决SpringBoot配置文件application.yml遇到的坑
    目录配置文件application.yml遇到的坑1.第一个坑,原代码解决办法2.第二个坑,原代码参见下图解决办法配置文件application.yml的注意事项这类似于还有一种配置...
    99+
    2022-11-13
  • Mybatis mapper标签中配置子标签package的坑及解决
    目录mapper标签中配置子标签package的坑Mybatis中mappers标签介绍配置方式1.接口所在包2.相对路径配置3.类注册引入4.使用URL绝对路径方式引入(不用)使用...
    99+
    2022-11-12
  • 解决SpringCloud Gateway配置自定义路由404的坑
    目录问题背景问题现象解决过程1 检查网关配置2 跟源码,查找可能的原因3 异常原因分析解决方法心得问题背景 将原有项目中的websocket模块迁移到基于SpringCloud Al...
    99+
    2022-11-12
  • 解决spring boot 配置文件后缀的一个坑
    目录spring boot 配置文件后缀的一个坑spring boot配置文件支持 properties和yml从新创建一个demo试试 spring boot 配置文件后缀导致启动...
    99+
    2022-11-12
  • Pytorch中retain_graph的坑如何解决
    本篇内容主要讲解“Pytorch中retain_graph的坑如何解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Pytorch中retain_graph的坑如何解决”吧!Pytorch中re...
    99+
    2023-07-05
  • Java中如何解决BigDecimal的坑
    这篇文章将为大家详细讲解有关Java中如何解决BigDecimal的坑,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。Java BigDecimal的坑采坑处BigDecimal bd ...
    99+
    2023-06-25
  • vue配置代理vue.config.js后不生效的解决(小坑)
    目录vue配置代理vue.config.js后不生效附上我的配置再对axios进行二次封装总结vue配置代理vue.config.js后不生效 我的项目使用vue-cli4脚手架搭建...
    99+
    2023-03-20
    vue配置代理 vue.config.js vue.config.js不生效
  • springboot配置文件自动转译的坑怎么解决
    本文小编为大家详细介绍“springboot配置文件自动转译的坑怎么解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“springboot配置文件自动转译的坑怎么解决”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧...
    99+
    2023-06-29
  • ScheduledThreadPoolExecutor的坑如何解决
    今天小编给大家分享一下ScheduledThreadPoolExecutor的坑如何解决的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了...
    99+
    2023-07-05
  • 如何解决spring jpa中update的坑
    这篇文章主要为大家展示了“如何解决spring jpa中update的坑”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何解决spring jpa中update的坑”这篇文章吧。spring j...
    99+
    2023-06-20
  • go中import包的坑如何解决
    这篇文章主要介绍“go中import包的坑如何解决”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“go中import包的坑如何解决”文章能帮助大家解决问题。方案一:使用GOROOT和GOPATH(以我...
    99+
    2023-07-02
  • electron打包中的坑如何解决
    这篇文章主要讲解了“electron打包中的坑如何解决”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“electron打包中的坑如何解决”吧!问题一:css文件中图片加载失败问题描述问题是这样...
    99+
    2023-07-05
  • 解决SpringBoot使用yaml作为配置文件遇到的坑
    目录SpringBoot yaml作为配置文件遇到的坑背景感觉修改一下比较好,类似这样:SpringBoot-yaml配置注入yaml基础语法字面量:普通的值 [ 数字,布尔值,字符...
    99+
    2022-11-12
  • vue项目配置element-ui容易遇到的坑及解决
    目录vue配置element-ui遇到的坑步骤1.npm安装步骤2步骤3.测试vue element-ui需要注意的问题vue配置element-ui遇到的坑 注意:本文章参照ele...
    99+
    2022-11-13
  • Java ScheduledThreadPoolExecutor的坑如何解决
    本篇内容介绍了“Java ScheduledThreadPoolExecutor的坑如何解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学...
    99+
    2023-07-04
  • 如何解决Go interface的坑
    本篇内容主要讲解“如何解决Go interface的坑”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何解决Go interface的坑”吧!例子一第一个例子,如下代码:func ma...
    99+
    2023-06-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作