如何在 java vertx 中编写自己的异步处理程序

how to write own async hander in java vertx

我想编写一个带有一些参数和一个 Handler<E> 对象的函数。在根据其他参数进行一些计算后,我需要 return 处理程序对象的结果。

为了更好的解释,我举个例子:

    public void getPlaces(LatLong latLong, int redius, Collection<PlaceType> places)
{
    if(redius <= 0 || redius > 50000)
    {
        throw new IllegalAccessError("redis can be 0 to 50000 meters only");
    }
    String uri = String.format(GOOGLE_PLACE_API_URI, latLong.getLatitude(), latLong.getLongitude(), redius, PROJECT_API_KEY, Joiner.on("|").join(places));


    HttpClientRequest request = httpClient.getAbs(uri, response ->{
        logger.info("Received response with status code={} message={}", response.statusCode(), response.statusMessage());
        response.bodyHandler( buffer -> {
            JsonObject result = buffer.toJsonObject();
            String nextPageToken = result.getString("next_page_token");
            JsonArray resultArray = result.getJsonArray("results");
            System.out.println("nextPageToken="+nextPageToken+" result="+resultArray);
        });

    }).setTimeout(30000);

    request.exceptionHandler(e -> {
        logger.error("Caught exception while making request for google place APIs. Error message={} e=", e.getMessage(), e);
    });
    request.end();
}

    public void getPlaces(LatLong latLong, int redius, Collection<PlaceType> places, Handler<JsonObject> response)
{
    // COMPLETE THIS USING ABOVE FUNCTION
    getPlaces(latLong, redius, places);
}

我不确定是否理解您的需求,但我猜您想用计算结果调用处理程序。所以这段代码应该做你想做的事:

public void getPlaces(LatLong latLong, int redius, Collection<PlaceType> places, Handler<JsonObject> handler) {

    if(redius <= 0 || redius > 50000) {
        throw new IllegalAccessError("redis can be 0 to 50000 meters only");
    }

    String uri = String.format(GOOGLE_PLACE_API_URI, latLong.getLatitude(), latLong.getLongitude(), redius, PROJECT_API_KEY, Joiner.on("|").join(places));

    HttpClientRequest request = httpClient.getAbs(uri, response ->{
        logger.info("Received response with status code={} message={}", response.statusCode(), response.statusMessage());
        response.bodyHandler( buffer -> {
            JsonObject result = buffer.toJsonObject();
            String nextPageToken = result.getString("next_page_token");
            JsonArray resultArray = result.getJsonArray("results");
            System.out.println("nextPageToken="+nextPageToken+" result="+resultArray);
            handler.handle(result); // call the result handler
        });

    }).setTimeout(30000);

    request.exceptionHandler(e -> {
        logger.error("Caught exception while making request for google place APIs. Error message={} e=", e.getMessage(), e);
    });
    request.end();
}

希望这会有所帮助。