2017-08-26 59 views
3

我正在使用Apache AVRO评估我的Jersey休息服务。我使用Springboot和Jersey休息。Apache AVRO与休息

目前我接受JSON作为输入whick jackson转换为Java pojos本身。

我已经看过不同的地方,但找不到任何使用Apache AVRO泽西端点的例子。

我发现这个Github链接https://github.com/FasterXML/jackson-dataformats-binary/它有Apache的avro插件。

我还找不到任何好的例子来说明如何整合?有没有人使用Apache AVRO和泽西岛。如果是,有没有我可以使用的例子?

+0

一些有用的链接:https://github.com/keedio/avro-schema-repo/tree/master/client/src/main/java/org/apache/avro/repo/client https://开头pastebin.com/DNS8xntG –

+0

您看过测试文件夹:https://github.com/FasterXML/jackson-dataformats-binary/tree/master/avro/src/test/java/com/fasterxml/jackson/ dataformat/avro? – bosco

回答

4

要开始,有两两件事需要发生:

  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使用杰克逊的消息处理程序:

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的响应选择此阅读器。

You can then inject the 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); 
    } 
} 

要回答你的最后的评论:在你的处理器Setting the mime type到建议的Avro /二进制应该做到这一点。

+0

谢谢。休息终点的产品和消费情况如何?我有@Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) – Makky

+1

不知道我理解你的问题,但我在这里提供的提供者示例不会影响服务实现类@Makky。看看我的更新是否提供了更多的清晰度 – kolossus

+0

我想我明白你现在指的是:设置MIME类型?查看更新@Makky – kolossus