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

com.base4j.cache.serializer.FstSerializer Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
package com.base4j.cache.serializer;

import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Fast-Serialization的实现
 */
public class FstSerializer implements Serializer {
    private static final Logger log = LoggerFactory.getLogger(FstSerializer.class);
    private static final FSTConfiguration CONF = FSTConfiguration.createDefaultConfiguration();

    @Override
    public byte[] serialize(final T value) {
        if (value == null) {
            return EMPTY_BYTES;
        }
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            FSTObjectOutput oos = CONF.getObjectOutput(os);
            oos.writeObject(value);
            oos.flush();

            return os.toByteArray();
        } catch (Exception e) {
            log.warn("序列化失败, value = {}", value, e);
            return EMPTY_BYTES;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                log.warn("序列化失败, value = {}", value, e);
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public T deserialize(final byte[] bytes) {
        if (SerializerTools.isEmpty(bytes)) {
            return null;
        }
        ByteArrayInputStream is = null;
        try {
            is = new ByteArrayInputStream(bytes);
            FSTObjectInput ois = CONF.getObjectInput(is);
            return (T) ois.readObject();
        } catch (Exception e) {
            log.warn("反序列化 bytes 失败.", e);
            return null;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.warn("反序列化 bytes 失败.", e);
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy