Apache AVRO与休息

Mak*_*kky 5 java rest jax-rs avro

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

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

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

我找到了这个包含Apache AVRO插件的Github存储库(https://github.com/FasterXML/jackson-dataformats-binary/).

我仍然找不到任何好的例子,如何整合它.有人用过泽西岛的Apache AVRO吗?如果是,是否有任何我可以使用的例子?

kol*_*sus 8

首先,需要做两件事:

  1. 您需要按照Avro架构格式的方式开发自定义ObjectMapper
  2. 您需要向Jersey 提供该自定义ObjectMapper.

这应该是这样的:

@Provider
public class AvroMapperProvider implements ContextResolver<ObjectMapper> {

    final AvroMapper avroMapper = new AvroMapper();

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return avroMapper;
    }
}
Run Code Online (Sandbox Code Playgroud)

配置您的应用程序以使用Jackson作为消息处理程序:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
         super(JacksonFeature.class,AvroMapperProvider.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以实现自定义,MessageBodyReader并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);
    }

}
Run Code Online (Sandbox Code Playgroud)

在这里,我们从假设的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);
    }
 }
Run Code Online (Sandbox Code Playgroud)

回答你的最后评论:将你的处理程序上的mime类型设置为推荐的avro/binary应该这样做.