物联网二进制数组优化内存及合并

在物联网合并帧的时候,有时候会有特定长度的二进制数据需要合并,这种合并很需要byte[]数组,然后因为物联网硬件设备特别多,非常容易造成OOM的情况。针对这种情况,我想通过对象池模式,来解决这个问题。

把所需的byte长度作为key,4就取byte[4]长度数组,5就取byte[5]长度数据!String类型考虑它的常量池特性!


项目地址:大衍物联: 这个框架的主要作用是解析各种协议!在数据解析中,有不同的协议类型。使用责任链模式,解析出不同的协议报文,并搭配使用,我在modbus中,解析出两种帧数据,一种是注册帧,注册帧内的设备id和设备通道绑定,一种是数据帧,数据帧里能得到设备通道信息,进而得到注册的设备id,根据设备id收发信息!获取完整一帧之后,要转化成model数据,我使用注解,参考FastJson,直接解码成对应的数据。


import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ByteArrayFactory {

    public static ConcurrentHashMap<String, ConcurrentLinkedQueue<byte[]>> hashLinkMap = new ConcurrentHashMap<>();

    /**
     * 根据长度,获取对应的byte[]数组
     * @param len
     * @return
     */
    public static byte[] getBytes(String len) {
        ConcurrentLinkedQueue<byte[]> queue = null;
        if(hashLinkMap.get(len) == null) {
            queue = new ConcurrentLinkedQueue();
            hashLinkMap.put(len,queue);
        }
        queue = hashLinkMap.get(len);
        byte[] buff =  queue.poll();
        if(buff == null) {
            buff = new byte[Integer.parseInt(len)];
        }
        return buff;
    }

    /**
     * 回收对应的byte[]数组
     * @param array
     */
    public static void recycle(byte[] array) {
        String len = array.length + "";
        for(int i =0; i < array.length; i++) {
            array[i] = 0x20;
        }
        ConcurrentLinkedQueue<byte[]> queue =  hashLinkMap.get(len);
        queue.offer(array);
    }




}

使用场景:

/**
 * 合并byte[] 数组
 * @param byteArray byte数组
 * @return 返回合并后的byte[]数组
 */
public static byte[] combinationContent(byte[]... byteArray)
{
    int len = 0;
    for(byte[] buff:byteArray)
    {
        len += buff.length;
    }
    ByteBuffer byteBuffer =  ByteBuffer.wrap(ByteArrayFactory.getBytes(len + "")); //ByteBuffer.allocate(len);
    for(byte[] buff:byteArray)
    {
        byteBuffer.put(buff);
    }
    byte[] buff = byteBuffer.array();
    return buff;
}

//合并二进制数据之后,它就可以回收了。
public static byte[] diandao(int value) {
    byte[] content =  DigitalConversion.integerConvertFourNumber(value);
    byte[] childFrame =  ByteCombination.combinationContent(diandaoHead,content,diandaoTail);
    ByteArrayFactory.recycle(content);
    return LargeScreenFrame.gatherPacket(childFrame);
}

有物联网技术讨论的,私信我交流学习下!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值