001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.components.serializer;
017
018import com.esotericsoftware.kryo.Kryo;
019import com.esotericsoftware.kryo.io.ByteBufferInput;
020import com.esotericsoftware.kryo.io.Output;
021import com.esotericsoftware.kryo.pool.KryoFactory;
022import com.esotericsoftware.kryo.pool.KryoPool;
023
024import java.io.ByteArrayOutputStream;
025
026/**
027 * @author Michael Yang 杨福海 (fuhai999@gmail.com)
028 * @version V1.0
029 * @Title: Kryo 序列化
030 * @Description: 性能和 fst一样
031 */
032public class KryoSerializer implements JbootSerializer {
033
034
035    private KryoFactory kryoFactory = () -> new Kryo();
036
037    private KryoPool kryoPool = new KryoPool.Builder(kryoFactory).
038            softReferences()
039            .build();
040
041    @Override
042    public byte[] serialize(Object obj) {
043        if (obj == null) {
044            return null;
045        }
046        Output output = null;
047        Kryo kryo = kryoPool.borrow();
048        try {
049            output = new Output(new ByteArrayOutputStream());
050            kryo.writeClassAndObject(output, obj);
051            return output.toBytes();
052        } finally {
053            if (output != null) {
054                output.close();
055            }
056            kryoPool.release(kryo);
057        }
058    }
059
060    @Override
061    public Object deserialize(byte[] bytes) {
062        if (bytes == null || bytes.length == 0) {
063            return null;
064        }
065        ByteBufferInput input = null;
066        Kryo kryo = kryoPool.borrow();
067        try {
068            input = new ByteBufferInput(bytes);
069            return kryo.readClassAndObject(input);
070        } finally {
071            if (input != null) {
072                input.close();
073            }
074            kryoPool.release(kryo);
075        }
076    }
077}