首页 > 数据库 >java @Cacheable生成的redisKey,出现两个连续的冒号::

java @Cacheable生成的redisKey,出现两个连续的冒号::

时间:2024-07-30 17:39:19浏览次数:7  
标签:Cacheable return String RedisCacheConfiguration redisKey cacheName keyPrefix jav

1、参考

基于redis2.1.6实现spring cache生成的key多出一个冒号

2、解决

需要对key进行处理,【重点】是computePrefixWith方法

        config = config.computePrefixWith(cacheName -> {
            return cacheName + StrUtil.COLON;
        });

以下是完整代码
实现 CacheKeyPrefix 接口的 String compute(String cacheName);方法,重写定义cache名称

    private RedisCacheConfiguration getRedisCacheConfiguration(Duration duration) {
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(duration)
                // .disableCachingNullValues()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        config = config.computePrefixWith(cacheName -> {
            // keyPrefix是cacheProperties设置的的redis前缀
            String keyPrefix = cacheProperties.getRedis().getKeyPrefix();
            if (StringUtils.hasText(keyPrefix)) {
                keyPrefix = keyPrefix.lastIndexOf(StrUtil.COLON) == -1 ? keyPrefix + StrUtil.COLON : keyPrefix;
                return keyPrefix + cacheName + StrUtil.COLON;
            }
            return cacheName + StrUtil.COLON;
        });

        return config;
    }

3、排查

在@Cacheable生成缓存key时,总是产生sys:cache:user::admin,多出两个冒号的情况

    @Override
    @Cacheable(cacheNames = CacheConstant.SYS_USERS_CACHE, key = "#username")
    public LoginUser getUserByName(String username) {
        if (org.jeecg.framework.common.util.CN.isEmpty(username)) {
            return null;
        }
        LoginUser loginUser = new LoginUser();
        SysUser sysUser = userMapper.getUserByName(username);
        if (sysUser == null) {
            return null;
        }
        BeanUtils.copyProperties(sysUser, loginUser);
        return loginUser;
    }

经过查看源码,发现defaultCacheConfig()生成的RedisCacheConfiguration对象

    public static RedisCacheConfiguration defaultCacheConfig() {
        return defaultCacheConfig((ClassLoader)null);
    }

    public static RedisCacheConfiguration defaultCacheConfig(@Nullable ClassLoader classLoader) {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
        registerDefaultConverters(conversionService);
        return new RedisCacheConfiguration(Duration.ZERO, true, true, CacheKeyPrefix.simple(), SerializationPair.fromSerializer(RedisSerializer.string()), SerializationPair.fromSerializer(RedisSerializer.java(classLoader)), conversionService);
    }

key的生成策略是simple()方法,其中String SEPARATOR = "::"; 明确是两个冒号,终于找到原因了

@FunctionalInterface
public interface CacheKeyPrefix {
    String SEPARATOR = "::";

    String compute(String cacheName);

    static CacheKeyPrefix simple() {
        return (name) -> {
            return name + "::";
        };
    }

    static CacheKeyPrefix prefixed(String prefix) {
        Assert.notNull(prefix, "Prefix must not be null!");
        return (name) -> {
            return prefix + name + "::";
        };
    }
}

标签:Cacheable,return,String,RedisCacheConfiguration,redisKey,cacheName,keyPrefix,jav
From: https://www.cnblogs.com/kikyoqiang/p/18333022

相关文章

  • Java使用EasyExcel自定义合并(横纵合并)、自定义行高列宽、自适应行高列宽工具Excel导出
    目录一、自适应行高列宽工具类1、自适应行高2、自适应列宽二、自定义行高列宽工具类1、自定义行高2、自定义列宽三、自定义合并工具类四、自定义样式五、实现Excel的完整代码最近又开始写Excel导出的业务,之前写的自适应行高列宽工具类并不满足现下的需求需求是导出......
  • [RoarCTF 2019]Easy Java
    [RoarCTF2019]EasyJavaStep1点击help按钮后发现:URL变成:url/Download?filename=help.docx而回显:java.io.FileNotFoundException:{help.docx}而当我尝试尝试POST,发现文件成功下载:Step2发现可能的漏洞点后,结合WEB-INF相关知识(见文末)可以下载WEB-INF/web.xmlPOST参数......
  • javaweb面向切面aop编程-实现自定义填充
    实现自定义填充注解@AutoFill创建annotation包,编写注解类点击查看代码/***自定义注解,用于标识某个方法需要进行功能字段自动填充处理*/@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@interfaceAutoFill{//数据库操作类型:UPDATEINSE......
  • java编译错误,找不到包的解决办法
    异常:D:\AC2024\20240729\delphiJIN_JAVA\JavaTest\bin\x64>javaMYclasses.JavaClassForDelphiTestExceptioninthread"main"java.lang.NoClassDefFoundError:com/sltas/front/third/util/CryptionUtilatMYclasses.JavaClassForDelphiTest.main(Jav......
  • JAVA介绍以及jdk、IDEA安装过程
    一.JavaME,JavaSE,JavaEEJavaME(MicroEdition):用途:JavaME是为嵌入式设备和移动设备(如手机、PDA)开发的版本。它专注于资源有限的设备和环境,提供了一个精简的Java运行时环境。特点:1.包含了一套精简的JavaAPI,使得开发者可以在资源受限的设备上运行Java应用程序。2.......
  • 我试图单击网站上的 java 脚本按钮,但它不起作用
    我通过lua中的这个脚本点击了按钮:functionmain(splash)splash:init_cookies(splash.args.cookies)splash.private_mode_enabled=falsesplash.images_enabled=true--Ensureimagesareloadedassert(splash:go{......
  • 在Java中利用GeoHash实现高效的‘附近xxx‘功能
    GeoHash的介绍GeoHash是一种高效的地理编码系统,它通过将地球表面划分为网格并用字母数字组合的字符串来表示每个区域。这种编码方法将二维的经纬度坐标转换为一维的字符串,使得地理位置的存储和检索变得更加简单。GeoHash的核心原理是将经纬度坐标转换为二进制,然后交替取位......
  • Java修炼 Java SE 面试题目 (简答) 2024.7.26 22:16
    目录1.基础知识2.控制流和循环3.集合框架4.异常处理5.多线程编程6.输入输出操作7.类和接口8.Lambda表达式和函数式编程9.内存管理和垃圾回收:10.Java虚拟机(JVM):1.基础知识解释Java的面向对象特性,如封装、继承和多态。Java的面向对象特性包括封装(将数据和代码封......
  • JavaScript の 闭包
    闭包概念:一个函数对周围状态的引用捆绑在一起,内层函数中访问到其外层函数的作用域(什么鸟语)简单理解就是:闭包=内层函数+外层函数的变量如functionouter(){leta=0functioninner(){a++console.log(a)}returninner}//这......
  • day11 Java基础——基本运算符
    day11Java基础——基本运算符小技巧:CTRL+D复制当前行到下一行例1:packageoperator;publicclassDemo01{publicstaticvoidmain(String[]args){//二元运算符inta=10;intb=20;intc=25;intd=25;......