带有 Rest 的 Apache AVRO

Apache AVRO with Rest

我正在评估将 Apache AVRO 用于我的 Jersey REST 服务。我正在将 Springboot 与 Jersey REST 一起使用。

目前我接受 JSON 作为输入,使用 Jackson 对象映射器将其转换为 Java Pojos。

我查看了不同的地方,但找不到任何使用 Apache AVRO 和 Jersey 端点的示例。

我找到了这个 Github 存储库 (https://github.com/FasterXML/jackson-dataformats-binary/),它有 Apache AVRO 插件。

我仍然找不到任何好的例子来说明如何整合它。有人在 Jersey 上使用过 Apache AVRO 吗?如果是,有没有我可以使用的例子?

首先,需要发生两件事:

  1. 您需要develop a custom ObjectMapper遵循 Avro 模式格式
  2. 您需要 supply that custom ObjectMapper 到泽西岛。

应该看起来像这样:

@Provider
public class AvroMapperProvider implements ContextResolver<ObjectMapper> {

    final AvroMapper avroMapper = new AvroMapper();

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return avroMapper;
    }
}

Configure your application 使用 Jackson 作为消息处理程序:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
         super(JacksonFeature.class,AvroMapperProvider.class);
    }
}

或者,您可以实现自定义 MessageBodyReader and MessageBodyWriter,允许您在进出途中直接处理有效负载:

public class AvroMessageReader implements MessageBodyReader<Person> {

    AvroSchema schema;

    final AvroMapper avroMapper = new AvroMapper();

    public AvroMessageReader(){
        schema = avroMapper.schemaFor(Person.class); //generates an Avro schema from the POJO class.
    }

    @Override
    public boolean isReadable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
        return type == Person.class; //determines that this reader can handle the Person class.
    }

    @Override
    public Person readFrom(Class<Person> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, String> mm, InputStream in) throws IOException, WebApplicationException {
        return avroMapper.reader(schema).readValue(in);
    }

}

在这里,我们从一个假设的人 class 生成一个 avro 模式。 JAX-RS 运行时将 select 这个 reader 基于来自 isReadable 的响应。

You can then inject the MessageBodyWorkers 组件到您的服务实现中 class:

@Path("app")
public static class BodyReaderTest{

    @Context
    private MessageBodyWorkers workers;

    @POST
    @Produces("avro/binary")
    @Consumes("avro/binary")
    public String processMessage() {

        workers.getMessageBodyReader(Person.class, Person.class, new Annotation[]{}, MediaType.APPLICATION_JSON_TYPE);
    }
 }

回答你最后的评论:Setting the mime type 推荐你的处理程序 avro/binary 应该这样做。

有一个关于如何在 JAX-RS REST 服务中使用 avro 的综合演示(我写的)at. The JAX-RS message body readers and writers for avro are implemented at and they do support avro binary, json, idiomatic json, csv where applicable. They do provide full support for schema evolution and projections (via the http accept header). There is a list of articles that explain in more detail the demonstrated concepts at. Also this demo project runs live on GKE at, you can browse at the openapi at。 Avro 在项目中用于一切,用于日志、指标、分析。