Springboot RedisTemplate 设置key 前缀

springboot 连接redis 并设置key前缀

properties中配置

#redis
redis.masterClusterNodes=10.40.57.197:7000;10.40.57.198:7002;10.40.57.199:7004
redis.slaveClusterNodes=10.40.57.197:7001;10.40.57.198:7003;10.40.57.199:7005
redis.maxTotal=50
redis.maxIdle=10
redis.minIdle=1
redis.maxWaitMillis=1000
redis.testOnBorrow=true
redis.testOnReturn=true
redis.timeout=10000
redis.lockExpireSeconds=5
redis.soTimeout=1000
redis.maxAttempts=3
redis.password=123456
redis.clientName=clientName

redis.keyPrefix=0000-->

读取配置文件内容:

@Component
@ConfigurationProperties(prefix = "redis")
@PropertySource("classpath:redis.properties")
public class RedisProperties {
    /**
     * master 节点数据
     */
    private String masterClusterNodes;
    /**
     * slave 节点数据
     */
    private String slaveClusterNodes;
    /**
     * 连接超时时间
     */
    private int timeout;
    /**
     * 获取数据超时时间
     */
    private int soTimeout;
    /**
     * 出现异常最大重试次数
     */
    private int maxAttempts;
    /**
     * 连接时使用的密码
     */
    private String password;

    private int maxTotal;
    private int maxIdle;
    private int minIdle;
    private int maxWaitMillis;

    private boolean testOnBorrow;
    private boolean testOnReturn;

    /**
     * key前缀
     */
    private String keyPrefix;
    sets,gets
    
}

自定义StringSerializer

这个还是需要优化的

@Component
public class MyStringSerializer implements RedisSerializer {

    private final Logger logger = LoggerFactory.getLogger ( this.getClass () );

    @Autowired
    private RedisProperties redisProperties;

    private final Charset charset;

    public MyStringSerializer() {
        this ( Charset.forName ( "UTF8" ) );
    }

    public MyStringSerializer(Charset charset) {
        Assert.notNull ( charset, "Charset must not be null!" );
        this.charset = charset;
    }

    @Override
    public String deserialize(byte[] bytes) {
        String keyPrefix = redisProperties.getKeyPrefix ();
        String saveKey = new String ( bytes, charset );
        int indexOf = saveKey.indexOf ( keyPrefix );
        if (indexOf > 0) {
            logger.info ( "key缺少前缀" );
        } else {
            saveKey = saveKey.substring ( indexOf );
        }
        logger.info ( "saveKey:{}",saveKey);
        return (saveKey.getBytes () == null ? null : saveKey);
    }

    @Override
    public byte[] serialize(String string) {
        String keyPrefix = redisProperties.getKeyPrefix ();
        String key = keyPrefix + string;
        logger.info ( "key:{},getBytes:{}",key, key.getBytes ( charset ));
        return (key == null ? null : key.getBytes ( charset ));
    }
}

redisConfig 配置

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    private final Logger logger = LoggerFactory.getLogger ( this.getClass () );

    @Autowired
    private RedisProperties redisProperties;
    @Autowired
    private MyStringSerializer myStringSerializer;
    
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory ( redisClusterConfiguration (),
                jedisPoolConfig () );
        jedisConnectionFactory.setPassword ( redisProperties.getPassword () );
        jedisConnectionFactory.setTimeout ( redisProperties.getTimeout () );
        return jedisConnectionFactory;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration() {
        String[] ipPorts = redisProperties.getClusterNodes ().split ( ";" );
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration ( Arrays.asList ( ipPorts
        ) );
        return redisClusterConfiguration;
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = BeanMapperUtil.map ( redisProperties,
                JedisPoolConfig.class );
        return jedisPoolConfig;
    }


    /**
     * 配置cacheManage
     * 设置超时时间  1小时
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager ( redisTemplate );
        redisCacheManager.setDefaultExpiration ( 60 * 60 );
        return redisCacheManager;
    }

    @Bean
    public RedisTemplate redisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate ( jedisConnectionFactory () );
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer ( Object.class );
        ObjectMapper om = new ObjectMapper ();
        om.setVisibility ( PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY );
        om.enableDefaultTyping ( ObjectMapper.DefaultTyping.NON_FINAL );
        jackson2JsonRedisSerializer.setObjectMapper ( om );
        template.setKeySerializer ( myStringSerializer );
        template.setHashKeySerializer ( myStringSerializer );
        template.setValueSerializer ( jackson2JsonRedisSerializer );
        template.afterPropertiesSet ();
        return template;
    }
}

你可能感兴趣的:(Springboot RedisTemplate 设置key 前缀)