当前位置: 首页 > 知识库问答 >
问题:

同时发送2个post请求,等待最多80毫秒的响应

易品
2023-03-14

我正在尝试发送两个post请求。两者应该同时发送(在我下面的当前代码中,可能是一个接一个地发送),并且应该等待最大80毫秒的响应,如果请求没有响应,则认为响应为空。

public void SendRequests(String requestString){

    TimeLimiter limiter1 = new SimpleTimeLimiter();
    Response response1 = null;
    System.out.println("Request Sent to 1");
    try{
        response1 = limiter1.callWithTimeout(new Callable<Response>() {
        public Response call() {

            //assume sendPost1 method will send POST request to some server and return response from server

            return sendPost1(requestString);
        }
      }, 80, TimeUnit.MILLISECONDS, true);
    }catch(Exception te){
        te.printStackTrace();
    }

    TimeLimiter limiter2 = new SimpleTimeLimiter();
    Response response2 = null;
    System.out.println("Request Sent to 2");
    try{
        response2 = limiter2.callWithTimeout(new Callable<Response>() {
            public Response call() {

                //assume sendPost2 method will send POST request to some server and return response from server


                return sendPost2(requestString);
            }
        }, 80, TimeUnit.MILLISECONDS, true);
    }catch(Exception te){
        te.printStackTrace();
    }

    //Do some process using response1 and response2

    }
}

我正在寻找一些方法来同时发送2个帖子请求并等待80ms的响应,如果没有响应,则将响应视为空。

@格雷,我试过你的解决方案如下。最初几分钟,我的servlet响应时间是2ms-10ms,但之后,它突然增加到200-300ms。

@WebServlet("/incomingTraffic")
public class ServletClass  extends HttpServlet {
Gson gson;
private static URL url1;
private static URL url2;

public Exchanger() {
    super();
}
public void init(ServletConfig config) throws ServletException {
    gson = new Gson();

    try{

    url1 = new URL( Constants.URL1 );
    url2 = new URL( Constants.URL2 );

    }catch(Exception e){

    } 

}

public void destroy() {
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletInputStream inputStream = request.getInputStream();
    Reader reader = new InputStreamReader(inputStream);

    //Request class is POJO
    final Request requestString = gson.fromJson(reader, Request.class);

    reader.close();
    //long start = System.currentTimeMillis();
    TimeLimiter limiter = new SimpleTimeLimiter();

    //Response class is POJO
    Response response1 = null;
    Response response2 = null;

    final ExecutorService threadPool = Executors.newCachedThreadPool();

    Future<Response> future1 = threadPool.submit(new Callable<Response>() {
        public Response call() {
            return sendPost1(requestString);
        }
    });
    Future<Response> future2 = null;

    if(Some Condition Satisfy){
        future2 = threadPool.submit(new Callable<Response>() {
            public Response call() {
                return sendPost2(requestString);
            }
        });
    }
    threadPool.shutdown();

    long start = System.currentTimeMillis();
    try {
        response1 = future1.get(80, TimeUnit.MILLISECONDS);
    } catch (ExecutionException ee) {
       // job threw exception
    } catch (InterruptedException ie) {
       // this (main?) thread was interrupted, good pattern to re-interupt
       Thread.currentThread().interrupt();
    } catch (TimeoutException te) {
       // wait timed out, maybe this is right?
        response1 = null;
       // try to interrupt the thread
       future1.cancel(true);
    }

    if(requestString.getImp().get(0).getVideo() != null){
    // wait for 80 MILLISECONDS minus how long we've been waiting for 2nd request
    long end = System.currentTimeMillis();
    //System.out.println(start+" - "+end);
    long wait = 80 + start - end;
    if (wait < 0) {
       wait = 0;
    }

    try {
        response2 = future2.get(wait, TimeUnit.MILLISECONDS);
    } catch (ExecutionException ee) {
       // job threw exception
    } catch (InterruptedException ie) {
       // this (main?) thread was interrupted, good pattern to re-interrupt
       Thread.currentThread().interrupt();
    } catch (TimeoutException te) {
       // wait timed out, maybe this is right?
        response2 = null;
       // try to interrupt the thread
       future2.cancel(true);
    }
    }
    try {
        threadPool.awaitTermination(80, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {

    }

    if(response1 == null && response2 == null){
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }else {
        response.setContentType("application/json");
        PrintWriter output = response.getWriter();
        response.setStatus(HttpServletResponse.SC_OK);
        if(Some Condition){
            response.getWriter().write(gson.toJson(response1));
        }
        else{
            response.getWriter().write(gson.toJson(response1));
        }
    }
        output.flush();
        output.close();
    }
}

protected Response sendPost2(Request request){
    Response response = null;
    String str = gson.toJson(request);
    HttpURLConnection conn = null;
    try{
        conn= (HttpURLConnection) url2.openConnection();           
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/json");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty( "Content-Length", Integer.toString(str.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(str);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();

        if(responseCode != 200){
            return null;
        }

        Reader reader = new InputStreamReader(conn.getInputStream());
        response = gson.fromJson(reader, Response.class);
        conn.disconnect();
    }catch(Exception e){
        e.printStackTrace();
        conn.disconnect();
    }

    return response;
}

protected Response sendPost1(Request request){
    Response response = null;
    String str = gson.toJson(request);
    HttpURLConnection conn = null;
    try{
        conn= (HttpURLConnection) url1.openConnection();           
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/json");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty( "Content-Length", Integer.toString(str.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(str);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();

        if(responseCode != 200){
            return null;
        }

        Reader reader = new InputStreamReader(conn.getInputStream());
        response = gson.fromJson(reader, Response.class);
        conn.disconnect();

    }catch(Exception e){
        e.printStackTrace();
        conn.disconnect();
    }

    return response;
}

}

共有1个答案

令狐良骏
2023-03-14

我正在寻找一些方法来同时发送2个帖子请求并等待80ms的响应,如果没有响应,则将响应视为空。

您当然可以将两者都作为Callable提交

final ExecutorService threadPool = Executors.newCachedThreadPool(NUM_THREADS);
...
Future<Response> future1 = threadPool.submit(new Callable<>() { ... });
Future<Response> future2 = threadPool.submit(new Callable<>() { ... });
// once you have submitted the last job you can shutdown the pool
threadPool.shutdown();

long start = System.currentTimeMillis();
try {
   response1 = future1.get(80, TimeUnit.SECONDS);
} catch (ExecutionException ee) {
   // job threw exception
} catch (InterruptedExeception ie) {
   // this (main?) thread was interrupted, good pattern to re-interupt
   Thread.currentThread().interrupt();
} catch (TimeoutException te) {
   // wait timed out, maybe this is right?
   response1 = null;
   // try to interrupt the thread
   future1.cancel(true);
}

// wait for 80 seconds minus how long we've been waiting for 2nd request
long wait = System.currentTimeMillis() - start - 80000;
if (wait < 0) {
   wait = 0;
}
try {
   response2 = future2.get(wait, TimeUnit.MILLISECONDS);
} catch (ExecutionException ee) {
   // job threw exception
} catch (InterruptedExeception ie) {
   // this (main?) thread was interrupted, good pattern to re-interrupt
   Thread.currentThread().interrupt();
} catch (TimeoutException te) {
   // wait timed out, maybe this is right?
   response2 = null;
   // try to interrupt the thread
   future2.cancel(true);
}

这将很好地工作,但诀窍是中断2个请求。仅仅中断线程不会杀死任何网络套接字或数据库连接。您必须确保作业可以自行测试中断状态,否则可能会泄漏线程。

 类似资料:
  • 我试图从比特币市场RESTful API中获取不同的JSON。 问题是:我只能将单个GET请求逐个发送到API,因此我无法同时从所有比特币市场获取所有数据。 有没有办法使用Python线程(每个线程使用不同的客户端端口发送GET请求)同时获取多个数据?

  • 我有一个骆驼endpoint,另一个应用程序在那里发送带有一些数据的post请求(可能是通过其他路由) 我想处理这个数据,并用POST请求的响应将一些东西返回给应用程序。 这就是我的骆驼上下文现在的样子: 如何通过post请求的响应从路由sendFinData发回一些应答?

  • 是否可以在不等待响应的情况下发送HTTP请求? 我在做一个物联网项目,需要记录传感器的数据。在每一个设置中,都有许多传感器,一个中央协调器(主要由Raspberry Pi实现)从传感器收集数据,并通过Internet将数据发送到服务器。 提前感谢! 编辑:传感器是无线的,但他们使用的技术在发送到协调器时很少(或没有)延迟。此协调器必须通过Internet发送数据。但是,假设互联网连接不好。因为这将

  • 请求方式: "|3|2|url,content|\r" 参数: url 设置Post请求的url链接 content post请求的数据 返回值: "|3|code|data|\r" 参数: code http请求返回的成功或者错误码 成功:code = 200 获取数据失败:code = -1 http请求字段错误:code = 1 data http请求返回的数据 Arduino样例: sof

  • 我在spring mvc 3.2.2中使用apache http客户端同步发送5个get请求,如图所示。 如何异步(并行)发送所有这些内容并等待请求返回,以便从所有 GET 请求返回已解析的有效负载字符串?

  • 我已经创建了一个简单的Jersey客户端,它能够成功地使用有效负载执行POST请求。但现在它正在等待来自httpendpoint的响应: 问:代码是否有可能不等待响应。 我试图阅读泽西客户端文档,以确定我的代码是否有可能不等待响应?我看到我们只能在读取响应后关闭连接,但在我的情况下没有用。我想在将有效负载发布到endpoint后立即关闭连接。 我只需要触发并忘记POST请求,因为我不关心响应。这是