简体   繁体   中英

How to send different web services requests to different destinations at the same time using Java?

I need to make different types of requests (RESTful and SOAP) at the same time using my Web application.

As I am newbie to this topic have been overwhelmed with information that I have found. I am wondering if it is possible, if yes how to implement it or what exactly should I look for?

Example

two method from Class A

a method from Class B

a method from Class C

User make a request and all these four methods make their request based on user's provided criteria send their requests at the same time to the their respective destination and receive the response.

You would need to multi-thread your application. Some helpful tutorials are available here and here .

Essentially, you would need to have 4 classes which extend the Thread class or implement the Runnable interface. The purpose of these classes would be to execute a request and eventually process the response from your services.

In your main class, you would simply need to create new instances of these 4 classes and spawn them off.

Have a look at the following code which I've found here

package com.scranthdaddy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) throws Exception {
        Main main = new Main();
        main.runBatchThreads();
    }

    private void runBatchThreads() {
        // initialize list of WebServiceTask objects
        List<WebServiceTask> webServiceTasks = new ArrayList<WebServiceTask>();

        for (int i = 0; i < 5000; i++) {
            WebServiceTask webServiceTask = new WebServiceTask();

            webServiceTasks.add(webServiceTask);
        }

        System.out.println("Starting threads");

        // create ExecutorService to manage threads
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        for (WebServiceTask webServiceTask : webServiceTasks) {
            // start thread
            executorService.execute(webServiceTask);
        }

        // shutdown worker threads when complete
        executorService.shutdown();

        System.out.println("Threads started, main ended");
    }
}

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