有没有办法将一种标识符用于异步请求?

时间:2019-06-10 03:50:27

标签: java asynchronous client-server

我有一个发送请求的服务器和一个客户端。在同步模式下运行时,我不需要识别请求。但是在异步模式下,每个请求都必须具有一个标识符,因此我可以确定响应与确切的请求相对应。服务器没有更新,我必须将标识符放在客户端的代码中。有办法吗?我什么都找不到。

这是我的主要课程。我想一切都必须清楚,该类非常简单。

public class MainAPITest {
    private static int userId = 0;
    private final static int NUM_OF_THREADS = 10;
    private final static int NUM_OF_USERS = 1000;

    public static void main(String[] args) {
        Security.addProvider(new GammaTechProvider());
        ExecutorService threadsExecutor = Executors.newFixedThreadPool(NUM_OF_THREADS);
        for (int i = 0; i < NUM_OF_USERS; i++) {
            MyRunnable user = new MyRunnable();
            userId++;
            user.uId = userId;
            threadsExecutor.execute(user);
        }
        threadsExecutor.shutdown();
    }
}

class MyRunnable implements Runnable {
    int uId;

    @Override
    public void run() {
        try {
            abstrUser user = new abstrUser();
            user.setUserId(uId);
            user.registerUser();
            user.chooseAndImplementTests();
            user.revokeUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

用户类描述用户的行为。它足够长,如果在这里需要,则为idk。用户运行许多随机测试。每个测试都有自己的类,该类扩展了抽象测试类,并在其中建立了http连接:

import org.json.JSONObject;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public abstract class abstractRESTAPITest {
    protected String apiUrl;

    public abstractRESTAPITest() {
    }

    protected byte[] sendRequest(JSONObject jsonObject) throws IOException {
        return this.sendRequest(jsonObject, (String) null, (String) null);
    }   

    protected byte[] sendRequest(JSONObject jsonObject, String username, String password) throws IOException {  
        HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(this.apiUrl)).openConnection();
        if (username != null && password != null) {
            String userPassword = username + ":" + password;
            httpURLConnection.setRequestProperty("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userPassword.getBytes()));
        }

        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setDoOutput(true);
        DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        dataOutputStream.write(jsonObject.toString().getBytes());
        dataOutputStream.flush();
        System.out.println("REST send: " + jsonObject.toString());
        if (httpURLConnection.getResponseCode() != 200) {
            System.out.println("REST send error, http code " + httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
            throw new IOException();
        } else {
            byte[] responseBody = null;
            StringBuilder data = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String line = "";

            while ((line = br.readLine()) != null) {
                data.append(line);
                responseBody = data.toString().getBytes();
            }

            if (br != null) {
                br.close();
            }
            return responseBody;
        }
    }   

    public abstract boolean test();

}

现在,我正在尝试将代码的httpUrlConnection部分转换为这种形式。

Jsonb jsonb = JsonbBuilder.create();

var client = HttpClient.newHttpClient();

var httpRequest = HttpRequest.newBuilder()
        .uri(new URI(apiUrl))
        .version(HttpClient.Version.HTTP_2)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(jsonb.toJson(jsonObject)))
        .build();

client.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());

它必须发送JSON请求并接收JSON响应。 Java11中引入的HttpClient具有sendAsync本机方法,因此我尝试使用它。但是我不完全了解它是如何工作的,所以我没有成功。

0 个答案:

没有答案