package com.elab.redis.serializers;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * @Module redis序列化
 * @Description 通用的序列化类,兼容fastjson、jackson两个版本
 * @Author liukaixiong
 * @Date 2021/1/18 15:33
 */
public class CompatibilityJsonRedisSerializer extends GenericFastJsonRedisSerializer {

    private GenericJackson2JsonRedisSerializer redisSerializer = new GenericJackson2JsonRedisSerializer();

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        Object deserialize = super.deserialize(bytes);
        if (deserialize != null && deserialize instanceof JSONObject) {
            String clazz = ((JSONObject) deserialize).getString("@class");
            if (clazz != null) {
                return redisSerializer.deserialize(bytes);
            }
        }
        return deserialize;
    }
}
