其他分享
首页 > 其他分享> > msgpack的使用

msgpack的使用

作者:互联网

1、引入包

        <!--msgpack依赖-->
        <dependency>
            <groupId>org.msgpack</groupId>
            <artifactId>msgpack</artifactId>
            <version>0.6.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.12.6</version>
            <scope>provided</scope>
        </dependency>

2、创建实体类

  注意,必须实现:Serializable,和@Message注解

package com.cyb.vo;

import lombok.Data;
import org.msgpack.annotation.Message;
import java.io.Serializable;

@Message
@Data
public class Member implements Serializable {
    private String mid;
    private String mname;
    private String mage;
}

3、方法使用

package com.cyb.test;

import com.cyb.vo.Member;
import org.msgpack.MessagePack;
import org.msgpack.template.Templates;

import java.util.ArrayList;
import java.util.List;

public class Test01 {
    public static void main(String[] args) throws Exception {
        Member member = new Member();
        member.setMid("101");
        member.setMname("alex");
        member.setMage("25");
        MessagePack msgPack = new MessagePack();
        byte[] data = msgPack.write(member); //将实体类数据转为Byte字节数组
        System.out.println(data.length); //打印字节数组长度
        //将实体类数据解析回来
        Member member1 = msgPack.read(data, Member.class);
        System.out.println(member1);
        //========解析实体类数组=============
        List<Member> allMemberList = new ArrayList<Member>();
        for (int x = 0; x < 5; x++) {
            Member m = new Member();
            m.setMid(x + "");
            m.setMname("sasa" + x);
            m.setMage("18");
            allMemberList.add(m);
        }
        MessagePack msgPack2 = new MessagePack();
        byte[] data2 = msgPack2.write(allMemberList);
        List<Member> all = msgPack2.read(data2, Templates.tList(msgPack2.lookup(Member.class)));
        System.out.println(all);
    }
}

标签:msgpack,org,使用,Member,new,import,MessagePack
来源: https://www.cnblogs.com/chenyanbin/p/12775554.html