我遇到的情况是,我需要为收到的每个请求返回“已接受”的响应,然后将实际响应发布到服务之外的单独端点。
为了实现“已接受”的响应,我实现了一个过滤器。
public class AcknowledgementFilter implements ContainerRequestFilter{
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
containerRequestContext.abortWith(Response.accepted().build());
// call Resource method in new Thread() . <------ ?
}
}
服务端点的实现:
@Path("/vendor")
public class VendorHandler {
@POST
public void addVendor(VendorRequest addVendorRequest)){
vendor = new Vendor();
Client.publish(vendor); // publish request to an endpoint
return null;
}
如何从确认过滤器调用VendorHandler的addVendor(或任何方法取决于请求)?
是否还有其他方法可以为每个请求实现接受的响应,然后单独处理请求?
答案 0 :(得分:0)
您可以使用AsyncResponse,
@GET
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
public void getLives(@Suspended final AsyncResponse asyncResponse,
@DefaultValue("0") @QueryParam("newestid") final int newestId,
@QueryParam("oldestid") final Integer oldestId) {
asyncResponse.setTimeoutHandler(asyncResponse1 -> {
logger.info("reached timeout");
asyncResponse1.resume(Response.ok().build());
});
asyncResponse.setTimeout(5, TimeUnit.MINUTES);
try {
List<Life> lives = oldestId == null ?
Lifes.getLastLives(newestId) : Lifes.getOlderLives(oldestId);
if (lives.size() > 0) {
final GenericEntity<List<Life>> entity = new GenericEntity<List<Life>>(lives) {
};
asyncResponse.resume(entity);
} else LifeProvider.suspend(asyncResponse);
} catch (SQLException e) {
logger.error(e, e);
asyncResponse.resume(new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
}
}
查看此Link了解详情。