Apache AVRO with Rest



我正在评估使用Apache AVRO进行Jersey REST服务。我正在使用带有Jersey REST的Springboot。

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

我看过不同的地方,但我找不到任何使用带有泽西岛终点的 Apache AVRO 的例子。

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

我仍然找不到任何关于如何集成它的好例子。有没有人将Apache AVRO与泽西岛一起使用?如果是,我可以使用任何示例吗?

首先,需要做两件事:

  1. 您需要按照 Avro 架构格式的时尚开发自定义ObjectMapper
  2. 您需要向泽西岛提供该自定义ObjectMapper

它应该看起来像这样:

@Provider
public class AvroMapperProvider implements ContextResolver<ObjectMapper> {
final AvroMapper avroMapper = new AvroMapper();
@Override
public ObjectMapper getContext(Class<?> type) {
return avroMapper;
}
}

将应用程序配置为使用 Jackson 作为消息处理程序:

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

或者,您可以实现自定义MessageBodyReaderMessageBodyWriter,允许您在进出过程中直接处理有效负载:

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);
}
}

在这里,我们从一个假设的 Person 类生成一个 avro 模式。JAX-RS 运行时将根据来自isReadable的响应选择此读取器。

然后,可以将MessageBodyWorkers组件注入到服务实现类中:

@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);
}
}

要回答您的最后一条评论:将处理程序上的 mime 类型设置为推荐的 avro/二进制应该可以做到这一点。

有一个关于如何在 JAX-RS REST 服务中使用 avro 的综合演示(我写的)。用于 avro 的 JAX-RS 消息体读取器和写入器在 实现,它们在适用的情况下支持 avro 二进制、json、习惯性 json、csv。它们确实为架构演变和投影提供了完全支持(通过 http accept 标头)。有一个文章列表,可以更详细地解释演示的概念。此外,这个演示项目在 GKE 上实时运行,您可以在 openapi 上浏览。Avro 在项目中用于所有内容、日志、指标和分析。

最新更新