我有一个 Jersey 服务,其中包含一个计时器任务,该任务轮询特定值。我只想在从轮询中获得特定值时才返回响应。有什么办法可以实现这一点吗?
我的代码是:
@Path("/poll")
public class PollService{
String response = null;
@GET
@Produces(javax.ws.rs.core.MediaType.TEXT_PLAIN)
public String pollResponse(@Context HttpServletRequest request){
MyTimer poller = new MyTimer();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(poller, 0, 5000);
return response;
}
private class MyTimer extends TimerTask{
@Override
public void run(){
//Poll
//Change value of response upon condition
}
}
在“response”变量的值设置为“SUCCESS”之前,我不希望服务返回任何值。我可以做什么来实现这个目标?
最佳答案
您可以采取的方法之一:
- 将您的请求分为两个请求
- 第一个请求将接受该请求并将发回 202 Accepted 响应。 202 resposne 将提供状态/轮询 url 来轮询异步任务结果
- 第二个请求将轮询提供的状态/轮询网址。作为响应,您可以返回 200 OK,正文为 IN_PROGRESS 或实际任务结果(如果完成)。
关于java - 如何在 Jersey 服务中返回特定响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19264151/