首先,需要发生两件事:
- 你需要制定一个习惯ObjectMapper https://github.com/FasterXML/jackson-dataformats-binary/tree/master/avro#creating-objectmapper遵循 Avro 模式格式的时尚
- 你需要供应该定制ObjectMapper https://jersey.github.io/documentation/latest/media.html#json到泽西岛。
那应该看起来像这样:
@Provider
public class AvroMapperProvider implements ContextResolver<ObjectMapper> {
final AvroMapper avroMapper = new AvroMapper();
@Override
public ObjectMapper getContext(Class<?> type) {
return avroMapper;
}
}
配置您的应用程序 https://jersey.github.io/documentation/latest/media.html#json使用 Jackson 作为消息处理程序:
public class MyApplication extends ResourceConfig {
public MyApplication() {
super(JacksonFeature.class,AvroMapperProvider.class);
}
}
或者,你可以实现一个自定义MessageBodyReader https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/MessageBodyReader.html and MessageBodyWriter https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/MessageBodyWriter.html这允许您直接处理传入和传出的有效负载:
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 https://jersey.github.io/documentation/latest/message-body-workers.html组件到您的服务实现类中:
@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 类型 https://avro.apache.org/docs/current/spec.html#HTTP+as+Transport在你的处理程序上推荐的 avro/binary 应该可以做到这一点。