我的要求:
我想制作像dropbox's
/longpoll_delta
这样的API,我在java jerser 2
中使用了restful
。实际上我想在服务器上发现更改时通知所有客户端。所以服务器可能需要2小时或更长时间,然后通知其所有客户端我有一些更新。出于安全考虑,我不想使用comet
,websocket
等。
1>建议我如何制作这样的API?
我的effor: 我创建了Asynchronous Server API
Server code:
@GET
@Path("/longpoll")
@ManagedAsync
public void async(@Suspended final AsyncResponse asyncResponse)
{
new Thread(new Runnable()
{
@Override
public void run()
{
String result = veryExpensiveOperation();
asyncResponse.resume(result);
}
private String veryExpensiveOperation()
{
try
{
// put some long running code here
Thread.sleep(60000);
return "Hello World";
}
catch (Exception e)
{
e.printStackTrace();
return "error";
}
}
}).start();
}
所以现在为了测试这个我创建了客户端
Client code:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
public class JersyClient
{
public static void main(String args[]) throws InterruptedException, ExecutionException
{
ClientConfig clientConfig = new ClientConfig();
Client client = ClientBuilder.newClient(clientConfig);
WebTarget target = client.target("http://localhost:8080");
Invocation.Builder invocationBuilder = target.path("MyApp_3_3_5/api/1/longpoll").request();
invocationBuilder.header("Authorization", "Bearer yBOrnV6zlOrgoYxrMsfQ_BYZ5p37gALB");
final Future<Response> future = invocationBuilder.async().get(new InvocationCallback<Response>()
{
@Override
public void completed(Response response)
{
System.out.println("Response status code "
+ response.getStatus() + " received.");
System.out.println("In response " + response.readEntity(String.class));
}
@Override
public void failed(Throwable throwable)
{
System.out.println("Invocation failed.");
throwable.printStackTrace();
}
});
Response response = future.get();
System.out.println("your response " + response.readEntity(String.class));
// get() waits for the response to be ready
System.out.println("Go ahead");
}
}
但这不能正常工作。
OutPut:
Response status code 200 received.
In response
your response
Go ahead
所以这里客户端不等待服务器在1分钟后发送的实际响应。