【问题标题】:How to set messageSize of ByteArrayRawSerializer to unlimited?如何将 ByteArrayRawSerializer 的 messageSize 设置为无限制?
【发布时间】:2017-11-03 19:54:05
【问题描述】:

我使用ByteArrayRawSerializer 作为套接字消息反序列化器。 消息结束总是由服务器关闭套接字来指示。

由于消息可能很大,我想无限地定义序列化程序的消息大小。但是怎么做呢?

以下导致缓冲区溢出错误:

ByteArrayRawSerializer s = new ByteArrayRawSerializer();
s.setMaxMessageSize(Integer.MAX_VALUE);

【问题讨论】:

标签: java spring spring-integration


【解决方案1】:

使用如此巨大的缓冲区大小是完全不切实际的,每个新请求都会尝试分配 > 2Gb 的内存。

您需要使用足够大的更合理的大小来处理您预期的消息大小。

或者,创建一个自定义解串器,根据需要分配更多缓冲区。

编辑

这是一个弹性原始反序列化器...

/*
 * Copyright 2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.integration.ip.tcp.serializer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.core.serializer.Deserializer;
import org.springframework.util.StreamUtils;

/**
 * A deserializer that uses an elastic {@link ByteArrayOutputStream}
 * instead of a fixed buffer. Completion is indicated by the sender
 * closing the socket.
 *
 * @author Gary Russell
 * @since 5.0
 *
 */
public class ByteArrayElasticRawDeserializer implements Deserializer<byte[]> {

    @Override
    public byte[] deserialize(InputStream inputStream) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamUtils.copy(inputStream, out);
        out.close();
        return out.toByteArray();
    }

}

【讨论】:

  • 那么是不是可以用无限的消息大小来初始化ByteArrayRawSerializer?其实我以前不知道消息大小。
  • Java 语言只允许Integer.MAX_VALUE 的缓冲区——即使这样,也只有当你有足够的内存时。 JVM 施加了进一步的限制Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
  • 原始反序列化器很简单;你需要一个更复杂的来根据需要分配内存(随着更多字节到达)。
  • 我用一个简单的弹性反序列化器更新了我的答案,其中缓冲区将按需增长。
  • 固定StreamUtils导入。
猜你喜欢
  • 2013-01-02
  • 1970-01-01
  • 2011-08-10
  • 2016-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
相关资源
最近更新 更多