使用Jackson序列和反序列化UserDetails对象

package com.security.SecurityDemo.common.utils;

import com.alibaba.fastjson.parser.ParserConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Redis使用Jackson序列化
 *
 * @author sg
 */
public class JacksonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    private ObjectMapper objectMapper;


    //static
    //{
    //    ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    //}

    public JacksonRedisSerializer(Class<T> clazz, ObjectMapper objectMapper) {
        super();
        this.clazz = clazz;
        this.objectMapper = objectMapper;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        try {
            return objectMapper.writeValueAsBytes(t);
        } catch (JsonProcessingException e) {
            throw new SerializationException("Could not serialize object: " + e.getMessage(), e);
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (IOException e) {
            throw new SerializationException("Could not deserialize object: " + e.getMessage(), e);
        }
    }

    protected JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}
package com.security.SecurityDemo.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.security.SecurityDemo.common.utils.FastJsonRedisSerializer;
import com.security.SecurityDemo.common.utils.JacksonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.text.SimpleDateFormat;

@Configuration
public class RedisConfig {

    //@Bean
    //@SuppressWarnings(value = { "unchecked", "rawtypes" })
    //public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    //{
    //    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    //    template.setConnectionFactory(connectionFactory);
    //
    //    FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);
    //
    //    // 使用StringRedisSerializer来序列化和反序列化redis的key值
    //    template.setKeySerializer(new StringRedisSerializer());
    //    template.setValueSerializer(serializer);
    //
    //    // Hash的key也采用StringRedisSerializer的序列化方式
    //    template.setHashKeySerializer(new StringRedisSerializer());
    //    template.setHashValueSerializer(serializer);
    //
    //    template.afterPropertiesSet();
    //    return template;
    //}


    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        // 创建一个 ObjectMapper 对象,用于配置序列化和反序列化的行为
        ObjectMapper objectMapper = new ObjectMapper();
        // 设置序列化时写入类名信息
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.WRAPPER_ARRAY);
        //objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        //
        //objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        //objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // 设置日期格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        JacksonRedisSerializer<Object> serializer = new JacksonRedisSerializer<>(Object.class, objectMapper);

        // 创建一个 GenericJacksonRedisSerializer 对象,用于序列化和反序列化
		//需要在反序列化的对象上加上@JsonIgnoreProperties(ignoreUnknown = true)注解
        //GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();

        // 设置 RedisTemplate 的默认序列化器为 JacksonRedisSerializer
        //redisTemplate.setDefaultSerializer(serializer);
        return template;
    }
}

posted @ 2024-02-26 01:30  ericdee  阅读(71)  评论(0编辑  收藏  举报