简体   繁体   English

将文档流发送到Jersey @POST端点

[英]Sending a stream of documents to a Jersey @POST endpoint

I want to be able to send a stream of a bunch of documents to a web service. 我希望能够一堆文档流发送到Web服务。 This will save on Http request/response overhead and focus on the documents themselves. 这将节省Http请求/响应开销并专注于文档本身。

In python you can do something like this: 在python中你可以这样做:

r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
    data={'track': 'requests'}, auth=('username', 'password'),
    stream=True)

for line in r.iter_lines():
    if line: # filter out keep-alive new lines
        print json.loads(line)

I'm looking for an example of someone streaming a Request to a Jersey rest api. 我正在寻找一个人将请求流式传输到泽西岛休息api的示例。 I was hoping to see the client side and the server side to show it working. 我希望看到客户端和服务器端显示它正常工作。 But i'm struggling hard to find an example out there. 但我很难找到一个例子。

The example Ideally would show: 理想情况下,该示例将显示:

Client:
  Open request
  Iterate over huge document list
    Write document to open request stream
  Close request

Server:
  @POST method
    Open entity stream
    Iterate over entity stream while next document is available
        Process document
    Close entity stream              

If we get it right you'll be processing entities on the Server while still sending them on the Client! 如果我们做对了,您将在服务器上处理实体,同时仍然在客户端上发送它们! Huge win! 巨大的胜利!

One of the simplest ways to accomplish this is to let Jersey provide the POST handler with an InputStream for the HTTP POST body. 实现此目的的最简单方法之一是让Jersey为POST POST处理程序提供一个用于HTTP POST主体的InputStream The method can use the InputStream and JSON parser of your choice to parse then handle each object. 该方法可以使用您选择的InputStream和JSON解析器来解析然后处理每个对象。

In the following example, the a Jackson ObjectReader produces a MappingIterator which parses and processes each Person document in the array as it is delivered to the server 在下面的示例中,一个Jackson ObjectReader生成一个MappingIterator ,它解析并处理数组中的每个Person文档,因为它被传递到服务器

/**
 * Parse and process an arbitrarily large JSON array of Person documents
 */
@Path("persons")
public static class PersonResource {

    private static final ObjectReader reader = new ObjectMapper().readerFor(Person.class);

    @Path("inputstream")
    @Consumes("application/json")
    @POST
    public void inputstream(final InputStream is) throws IOException {
        final MappingIterator<Person> persons = reader.readValues(is);
        while (persons.hasNext()) {
            final Person person = persons.next();
            // process
            System.out.println(person);
        }
    }
}

Likewise, the Jersey client framework can send a stream of documents when configured with a Jackson ObjectMapper . 同样,Jersey客户端框架可以在配置Jackson ObjectMapper时发送文档流。 The following example demonstrates this with the Jersey Test framework. 以下示例使用Jersey Test框架演示了这一点。 The client streams an arbitrarily large iterator of Person documents 客户端流式传输Person文档的任意大迭代器

public class JacksonStreamingTest extends JerseyTest {

    @Override
    protected Application configure() {
        return new ResourceConfig(PersonResource.class, ObjectMapperProvider.class);
    }

    /**
     * Registers the application {@link ObjectMapper} as the JAX-RS provider for application/json
     */
    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    public static class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

        private static final ObjectMapper mapper = new ObjectMapper();

        public ObjectMapper getContext(final Class<?> objectType) {
            return mapper;
        }
    }

    @Override
    protected void configureClient(final ClientConfig config) {
        config.register(ObjectMapperProvider.class);
    }

    @Test
    public void test() {
        final Set<Person> persons = Collections.singleton(Person.of("Tracy", "Jordan"));
        final Response response = target("persons/inputstream").request().post(Entity.json(persons.iterator()));
        assertThat(response.getStatus()).isEqualTo(204);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM