网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Kryo序列化及反序列化用法示例

Kryo 是一个快速高效的 Java 对象图形序列化框架,主要特点是性能、高效和易用。该项目用来序列化对象到文件、数据库或者网络。

我们提供的服务有:成都做网站、网站设计、外贸营销网站建设、微信公众号开发、网站优化、网站认证、乌鲁木齐ssl等。为近1000家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的乌鲁木齐网站制作公司

    代码地址:https://github.com/EsotericSoftware/kryo

    样例代码地址:https://github.com/nettm/public

    Kryo的序列化及反序列速度很快,据说很多大公司都在用。我在把对象序列化都转换成了字符串形式,是为了把对象存储到缓存中。我们日常项目中使用的数据形式包括对象、List、Set和Map,因此主要把这几种类型的数据进行了序列化及反序列化,支持对象中包含List、Set和Map。

首先在项目的pom文件中引入:


  com.esotericsoftware
  kryo-shaded
  3.0.3

代码KryoTest:

package com.nettm.serializable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.esotericsoftware.kryo.serializers.MapSerializer;
public class KryoTest {
  private long time;
  @BeforeTest
  public void beforeTest() {
    time = System.currentTimeMillis();
  }
  @AfterTest
  public void afterTest() {
    System.out.println(System.currentTimeMillis() - time);
  }
  @Test(invocationCount = 1, threadPoolSize = 1)
  public void testObject() {
    CustomItemDto val = new CustomItemDto();
    val.setId(Long.parseLong(String.valueOf(1)));
    val.setItemCode("");
    val.setItemDespositPrice(32.45);
    val.setItemMemo(null);
    val.setItemName("张金");
    val.setItemPrice(89.02);
    val.setSort(10);
    String a = serializationObject(val);
    CustomItemDto newValue = deserializationObject(a, CustomItemDto.class);
    Assert.assertEquals(val.getId(), newValue.getId());
  }
  @Test(invocationCount = 1, threadPoolSize = 1)
  public void testList() {
    List lst = new ArrayList();
    for (int i = 0; i < 10; i++) {
      CustomItemDto val = new CustomItemDto();
      val.setId(Long.parseLong(String.valueOf(i)));
      val.setItemCode("");
      val.setItemDespositPrice(32.45);
      val.setItemMemo(null);
      val.setItemName("张金");
      val.setItemPrice(89.02);
      val.setSort(10);
      lst.add(val);
    }
    String a = serializationList(lst, CustomItemDto.class);
    List newValue = deserializationList(a,
        CustomItemDto.class);
    Assert.assertEquals(lst.size(), newValue.size());
  }
  @Test(invocationCount = 1, threadPoolSize = 1)
  public void testBean() {
    List lst = new ArrayList();
    for (int j = 0; j < 10; j++) {
      CustomCategoryDto dto = new CustomCategoryDto();
      dto.setCategoryCode("ABCD_001");
      dto.setCategoryName("呼吸系统");
      for (int i = 0; i < 10; i++) {
        CustomItemDto val = new CustomItemDto();
        val.setId(Long.parseLong(String.valueOf(i)));
        val.setItemCode("");
        val.setItemDespositPrice(32.45);
        val.setItemMemo(null);
        val.setItemName("张金");
        val.setItemPrice(89.02);
        val.setSort(10);
        dto.getCustomItemList().add(val);
      }
      for (int i = 0; i < 10; i++) {
        CustomItemDto val = new CustomItemDto();
        val.setId(Long.parseLong(String.valueOf(i)));
        val.setItemCode("");
        val.setItemDespositPrice(32.45);
        val.setItemMemo(null);
        val.setItemName("张金");
        val.setItemPrice(89.02);
        val.setSort(10);
        dto.getCustomItemSet().add(val);
      }
      for (int i = 0; i < 10; i++) {
        CustomItemDto val = new CustomItemDto();
        val.setId(Long.parseLong(String.valueOf(i)));
        val.setItemCode("");
        val.setItemDespositPrice(32.45);
        val.setItemMemo(null);
        val.setItemName("张金");
        val.setItemPrice(89.02);
        val.setSort(10);
        dto.getCustomItemMap().put(String.valueOf(i), val);
      }
      lst.add(dto);
    }
    String a = serializationList(lst, CustomCategoryDto.class);
    List newValue = deserializationList(a,
        CustomCategoryDto.class);
    Assert.assertEquals(lst.size(), newValue.size());
  }
  @Test(invocationCount = 1, threadPoolSize = 1)
  public void testMap() {
    Map map = new HashMap();
    for (int i = 0; i < 10; i++) {
      CustomItemDto val = new CustomItemDto();
      val.setId(Long.parseLong(String.valueOf(i)));
      val.setItemCode("");
      val.setItemDespositPrice(32.45);
      val.setItemMemo(null);
      val.setItemName("张金");
      val.setItemPrice(89.02);
      val.setSort(10);
      map.put(new ObjectId().toString(), val);
    }
    String a = serializationMap(map, CustomItemDto.class);
    Map newValue = deserializationMap(a,
        CustomItemDto.class);
    Assert.assertEquals(map.size(), newValue.size());
  }
  @Test(invocationCount = 1, threadPoolSize = 1)
  public void testSet() {
    Set set = new HashSet();
    for (int i = 0; i < 10; i++) {
      CustomItemDto val = new CustomItemDto();
      val.setId(Long.parseLong(String.valueOf(i)));
      val.setItemCode("");
      val.setItemDespositPrice(32.45);
      val.setItemMemo(null);
      val.setItemName("金星");
      val.setItemPrice(89.02);
      val.setSort(10);
      set.add(val);
    }
    String a = serializationSet(set, CustomItemDto.class);
    Set newValue = deserializationSet(a, CustomItemDto.class);
    Assert.assertEquals(set.size(), newValue.size());
  }
  private  String serializationObject(T obj) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.register(obj.getClass(), new JavaSerializer());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Output output = new Output(baos);
    kryo.writeClassAndObject(output, obj);
    output.flush();
    output.close();
    byte[] b = baos.toByteArray();
    try {
      baos.flush();
      baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return new String(new Base64().encode(b));
  }
  @SuppressWarnings("unchecked")
  private  T deserializationObject(String obj,
      Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.register(clazz, new JavaSerializer());
    ByteArrayInputStream bais = new ByteArrayInputStream(
        new Base64().decode(obj));
    Input input = new Input(bais);
    return (T) kryo.readClassAndObject(input);
  }
  private  String serializationList(List obj,
      Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.setRegistrationRequired(true);
    CollectionSerializer serializer = new CollectionSerializer();
    serializer.setElementClass(clazz, new JavaSerializer());
    serializer.setElementsCanBeNull(false);
    kryo.register(clazz, new JavaSerializer());
    kryo.register(ArrayList.class, serializer);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Output output = new Output(baos);
    kryo.writeObject(output, obj);
    output.flush();
    output.close();
    byte[] b = baos.toByteArray();
    try {
      baos.flush();
      baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return new String(new Base64().encode(b));
  }
  @SuppressWarnings("unchecked")
  private  List deserializationList(String obj,
      Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.setRegistrationRequired(true);
    CollectionSerializer serializer = new CollectionSerializer();
    serializer.setElementClass(clazz, new JavaSerializer());
    serializer.setElementsCanBeNull(false);
    kryo.register(clazz, new JavaSerializer());
    kryo.register(ArrayList.class, serializer);
    ByteArrayInputStream bais = new ByteArrayInputStream(
        new Base64().decode(obj));
    Input input = new Input(bais);
    return (List) kryo.readObject(input, ArrayList.class, serializer);
  }
  private  String serializationMap(
      Map obj, Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.setRegistrationRequired(true);
    MapSerializer serializer = new MapSerializer();
    serializer.setKeyClass(String.class, new JavaSerializer());
    serializer.setKeysCanBeNull(false);
    serializer.setValueClass(clazz, new JavaSerializer());
    serializer.setValuesCanBeNull(true);
    kryo.register(clazz, new JavaSerializer());
    kryo.register(HashMap.class, serializer);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Output output = new Output(baos);
    kryo.writeObject(output, obj);
    output.flush();
    output.close();
    byte[] b = baos.toByteArray();
    try {
      baos.flush();
      baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return new String(new Base64().encode(b));
  }
  @SuppressWarnings("unchecked")
  private  Map deserializationMap(
      String obj, Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.setRegistrationRequired(true);
    MapSerializer serializer = new MapSerializer();
    serializer.setKeyClass(String.class, new JavaSerializer());
    serializer.setKeysCanBeNull(false);
    serializer.setValueClass(clazz, new JavaSerializer());
    serializer.setValuesCanBeNull(true);
    kryo.register(clazz, new JavaSerializer());
    kryo.register(HashMap.class, serializer);
    ByteArrayInputStream bais = new ByteArrayInputStream(
        new Base64().decode(obj));
    Input input = new Input(bais);
    return (Map) kryo.readObject(input, HashMap.class,
        serializer);
  }
  public static  String serializationSet(Set obj,
      Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.setRegistrationRequired(true);
    CollectionSerializer serializer = new CollectionSerializer();
    serializer.setElementClass(clazz, new JavaSerializer());
    serializer.setElementsCanBeNull(false);
    kryo.register(clazz, new JavaSerializer());
    kryo.register(HashSet.class, serializer);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Output output = new Output(baos);
    kryo.writeObject(output, obj);
    output.flush();
    output.close();
    byte[] b = baos.toByteArray();
    try {
      baos.flush();
      baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return new String(new Base64().encode(b));
  }
  @SuppressWarnings("unchecked")
  public static  Set deserializationSet(
      String obj, Class clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.setRegistrationRequired(true);
    CollectionSerializer serializer = new CollectionSerializer();
    serializer.setElementClass(clazz, new JavaSerializer());
    serializer.setElementsCanBeNull(false);
    kryo.register(clazz, new JavaSerializer());
    kryo.register(HashSet.class, serializer);
    ByteArrayInputStream bais = new ByteArrayInputStream(
        new Base64().decode(obj));
    Input input = new Input(bais);
    return (Set) kryo.readObject(input, HashSet.class, serializer);
  }
}

总结

以上就是本文关于Kryo序列化及反序列化用法示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:java原生序列化和Kryo序列化性能实例对比分析 、 Kryo框架使用方法代码示例等,有什么问题可以随时留言,小编一定竭尽所能,答您所问。


名称栏目:Kryo序列化及反序列化用法示例
浏览路径:http://bjjierui.cn/article/ijheos.html

其他资讯