简体   繁体   中英

Java Timeout Line of code calling soap connection

Hello I am executing a soap request. I want to run this line of code.

int flag=5seconds;

//the line below doesnt come back within 5 seconds) cancel the 3rd party api call using soap and just continue

if(time for 5 seconds) this.soapResponse = soapConnection.call(createSOAPRequest(value), url);

else terminate and continue with rest of code.

I need to store the soapResponse so calling other functions or classs that can allow me to pass the object back would be bad. I want a simple way of making sure that the line executes within the time set by a flag. Could I create a thread and wait that 5 seconds. if it doesnt come back then just end the while loop

while(count to 5 seconds){
    this.soapResponse = soapConnection.call(createSOAPRequest(value), url);
}

Yes, you can create a thread for this. You can use this class in order to realize a timeout. You need to wrap the SOAP connection call in a Runnable (or even better, a Callable<Response> because you want to return a value):

public class SoapRunnable implements Runnable {
    private String value;
    private String url;
    private Connection soapConnection;
    private Response<?> response;

    public SoapCallable(Connection soapConnection, String value, String url) {
        this.url = url;
        this.value = value;
        this.soapConnection = soapConnection;
    }

    @Override
    public void run() {
        response = soapConnection.call(createSOAPRequest(value), url);
    }

    public Response<?> getResponse() {
        return response;
    }
}

You can then create an instance of SoapRunnable and pass it to the TimeoutController method:

   try {
      TimeoutController.execute(soapRunnable, 5000);
      // Call succeeded, grab result
      this.soapResponse = soapRunnable.getResponse();
   } catch (TimeoutException e) {
      // call did not return within 5 seconds, proceed with "else" code
   }

You can use the following properties to set timeout.

Connection timeout is time taken to connect to third party server and read time out is time taken by third party after connecting and returning response.


    int connectionTimeOutInMs = 5000;
    int readTimeOutInMs = 5000;
    context.put("javax.xml.ws.client.connectionTimeout", connectionTimeOutInMs);    
    context.put("javax.xml.ws.client.receiveTimeout", readTimeOutInMs);
    context.put("com.sun.xml.internal.ws.request.timeout", connectionTimeOutInMs);
    context.put("com.sun.xml.ws.request.timeout", connectionTimeOutInMs);
    context.put("com.sun.xml.ws.connect.timeout", connectionTimeOutInMs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM