【问题标题】:How to set redis cache prefix key for non spring boot java application using xml configuration如何使用xml配置为非spring boot java应用程序设置redis缓存前缀键
【发布时间】:2021-05-23 16:11:18
【问题描述】:

我想为我的应用程序设置一个自定义缓存键前缀,它为我的 RedisCacheManager 使用 xml 配置,我的目标是,如果缓存键是学生详细信息,则缓存键应该是 test :: student-detail 或 prod :: student-detail,我已经将usePrefix设置为true,但是我找不到定义实际键值的方法。下面是我的 cacheManager 配置的摘录。

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
      c:redisOperations-ref="redisTemplate"
      c:defaultExpiration=3600
      c:usePrefix="true">
</bean>

关于信息,我知道在spring boot中就像在应用程序属性中设置一个属性一样简单:

spring.cache.redis.key-prefix=some::
spring.cache.redis.use-key-prefix=true

只是为了说明我为什么要针对非 Spring Boot Java 应用程序。

【问题讨论】:

    标签: java spring-data-redis redis-cache wildfly-18


    【解决方案1】:

    解决方案是通过实现RedisCachePrefix来创建你的自定义redis缓存前缀。见下面的代码

    package com.cache.custom.utils;
    
    import com.morgan.design.properties.ReloadableProperty;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.cache.RedisCachePrefix;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    public class MyRedisCachePrefix implements RedisCachePrefix {
    /** The Prefix */
    @ReloadableProperty("prefixString")
    private String personalPrefixString;
    
    /** The key string redis serializer */
    @Autowired
    String StringRedisSerializer stringRedisSerializer;
    
    /** The delimiter */
    private final String delimiter = "::";
    
    @Override
    public byte[] prefix(String cacheName) {
      return stringRedisSerializer.serialize(personalPrefixString.concat(":").concat(cacheName).concat(this.delimiter));
    }
    }
    

    然后在xml上:

    <bean id=stringRedisSerializer"
          class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    <bean id="redisCachePrefix"
          class="com.cache.custom.utils.MyRedisCachePrefix"/>
    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
          c:redisOperations-ref="redisTemplate"
          p:defaultExpiration=3600
          p:usePrefix="true"
          p:cachePrefix-ref="redisCachePrefix"
    >
    </bean>
    

    N.B:personalPrefixString 值将从前缀字符串的属性文件条目中获取。 如果 prefixString 值是 testing 并且 cacheName 是 student-details-cache 那么你的缓存键将以 : testing:student-details-cache::

    为前缀

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2015-04-01
      • 2016-06-17
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2017-04-16
      相关资源
      最近更新 更多