All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.admin4j.redis.factory.RedisSerializerFactory Maven / Gradle / Ivy

Go to download

redis序列化器自动装配starter。默认使用jackson,支持fastjson,fastjson2

There is a newer version: 0.10.0
Show newest version
package com.admin4j.redis.factory;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author andanyang
 * @since 2023/5/16 11:11
 */
public class RedisSerializerFactory {

    public static  RedisTemplate defaultRedisSerializer(RedisConnectionFactory connectionFactory) {
        //jackson序列化工具
        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);

        return serializer(connectionFactory, jackson2JsonRedisSerializer);

    }

    public static  RedisTemplate serializer(RedisConnectionFactory connectionFactory, RedisSerializer serializer) {

        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(serializer);
        template.setDefaultSerializer(RedisSerializer.string());
        template.afterPropertiesSet();
        return template;
    }
}