package com.community.commom.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

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

/**
 * redis fastjson 序列化工具
 * @author gengxiang
 * @create 2017-09-06 18:04
 *
 **/
@Component
public class FastJsonSerializer implements RedisSerializer {


    @Override
    public <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException {
        try {
            if (source == null){
                return null;
            }
            if (tClass == String.class){
                return tClass.cast(new String(source, Charset.forName("UTF-8")));
            }

            return JSON.parseObject(source,tClass);
        } catch (Exception e) {
            throw new SerializationFailedException("Deserialize failed:" + e, e);
        }
    }

    @Override
    public byte[] serialize(Object object) throws SerializationFailedException {
        if (!(object instanceof Serializable)) {
            throw new IllegalArgumentException("Serializer requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]");
        }
        try {
            if (object instanceof String){
                return object.toString().getBytes("UTF-8");
            }
            return JSON.toJSONString(object).getBytes("UTF-8");
        } catch (Exception e) {
            throw new SerializationFailedException("Serialize failed:" + object.getClass(), e);
        }
    }
}
