【发布时间】:2017-12-30 04:34:43
【问题描述】:
我正在尝试找到一种异步方式来立即返回对客户端请求的响应。
我只需要记录请求数据,调用新线程在其他服务器上请求昂贵的操作(一些后端操作) 并且不等待他们的响应立即返回 200 状态响应给客户端。
此时我正在尝试使用 CompletableFuture 来实现,但我错过了一些东西。
package com.example.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.concurrent.CompletableFuture;
@Path("/class")
public class AsynchronousResponse {
private static final Logger LOGGER = (Logger) LogManager.getLogger(AsynchronousResponse.class.getName());
private static final int HTTP_STATUS_OK = 200;
private static final String EMPTY_CONTENT = "";
@Context
private HttpServletRequest httpRequest;
@Path("/method")
@GET
@Consumes(MediaType.APPLICATION_JSON)
public Response asyncResponseSupply() {
LOGGER.info(httpRequest.getSession().getId() + " : New session received");
CompletableFuture.supplyAsync(this::veryExpensiveOperations);
LOGGER.info(httpRequest.getSession().getId() + " : Returning empty response... ");
return Response.status(HTTP_STATUS_OK).entity(EMPTY_CONTENT).build();
}
// need to do some operations on data from httpRequest
private String veryExpensiveOperations() {
LOGGER.info(httpRequest.toString());
LOGGER.info("Start very expensive operations");
try {
Thread.sleep(3000);
LOGGER.info("Finished");
return "DONE";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
LOGGER.error("Error: " + e.getMessage());
return "ERROR";
}
}
}
总而言之,我会立即得到响应,但是 veryExpensiveOperations() 方法似乎丢失了 httpRequest 值,这对我来说太糟糕了,因为我需要使用来自客户端请求的值调用其他 Web 服务。感谢您的帮助!
对于我的应用,我使用的是 Jetty ver。 9.2.18.v20160721
【问题讨论】:
标签: java asynchronous java-8 jetty completable-future