3 自定义序列化

Wu Jun 2019-01-05 17:03:29
11 分布式 > 03 分布式存储 > 03 Redis
/**
 * @author wujun
 * @date 2018-10-30 16:25
 */
@Configuration
public class RedisConfig {
    /**
     * redisTemplate 自定义序列化类
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        Jackson2JsonRedisSerializer<Object> 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);

        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

scan 获取 key

    public void getKeys() {
        Set<String> keys = redisTemplate.execute((RedisCallback<Set<String>>) connection -> {

            Set<String> result = new HashSet<>();

            //cursor 用完要 close
            try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(ZSET_KEY_PREFIX + "*").count(100).build())) {
                while (cursor.hasNext()) {
                    byte[] bytes = cursor.next();
                    result.add(new String(bytes, StandardCharsets.UTF_8));
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return result;
        });

    }