【问题标题】:How to send/receive data in avro format from jersey?如何从球衣发送/接收 avro 格式的数据?
【发布时间】:2014-07-21 12:45:13
【问题描述】:

我有一组使用jersey 开发的网络服务,目前网络服务以JSON 格式发送和接收数据。为了提高处理时间和所需内存方面的性能,我们正在试验Protobufavro

我找到了一些教程,这些教程展示了将protobuf 集成到此类 Web 服务中是多么容易。但我找不到这样的教程或任何书,至少可以让我们了解我们是否可以使用jersey 发送/接收avro 格式的数据。

我想知道如何使用jersey 发送/接收avro 格式的数据。

【问题讨论】:

    标签: json performance protocol-buffers jersey-2.0 avro


    【解决方案1】:

    我有一个类似的问题,我很惊讶两年来没有其他人找到解决方案。我们使用的是 Jersey 2.x,我使用了 Provider 来处理 Avro。

    如果您生成代码,则此 sn-p 有效。如果你不这样做,你必须使用 GenericDatumReader/WriterGenericRecord 而不是 SpecificDataReader/WriterSpecificRecord

    还要注意 Avro 规范说使用 avro/binary 作为内容类型,尽管有一个 6 岁的 JIRA ticket 来更改它,因为它是无效类型。

    为了简单起见,我对其进行了精简,因此其中没有错误处理。如果您有一个常见的ExceptionMapper 来捕获一般异常,请小心,因为它不知道如何生成 avro 二进制文件。

    @Provider
    @Consumes("avro/binary")
    @Produces("avro/binary")
    public class AvroProvider <T extends SpecificRecord> implements MessageBodyWriter<T>, MessageBodyReader<T>
    {
        public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
                final MediaType mediaType)
        {
            return SpecificRecord.class.isAssignableFrom(type);
        }
    
        public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
                final MediaType mediaType)
        {
            return true;
        }
    
        @Override
        public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
                throws IOException, WebApplicationException
        {
            DatumReader<T> reader = new SpecificDatumReader<>(type);
            Decoder decoder = DecoderFactory.get().binaryDecoder(entityStream, null);
            return reader.read(null, decoder);
        }
    
        @SuppressWarnings("unchecked")
        @Override
        public void writeTo(T message, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
                throws IOException, WebApplicationException
        {
          DatumWriter<T> datumWriter = new SpecificDatumWriter<>((Class<T>)type);
          Encoder encoder = EncoderFactory.get().binaryEncoder(entityStream, null);
          datumWriter.write(message, encoder);
          encoder.flush();
        }
    
        @Override
        public long getSize(T message, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
        {
            return -1;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-25
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 2014-03-20
      • 1970-01-01
      相关资源
      最近更新 更多