在客户端代码中实现同步和异步行为的更好方法?

时间:2013-12-29 04:12:34

标签: java multithreading asynchronous future

我正在开展一个项目,我应该在其中对我的客户进行synchronousasynchronous行为。一般来说,我们的客户如何工作如下 -

客户将使用userId呼叫我们的客户,我们将从userId构建一个URL并对该URL进行HTTP调用,我们将在点击URL后返回一个JSON字符串。在我们将响应作为JSON字符串返回之后,我们将该JSON字符串发送回给我们的客户。

所以在这种情况下,正如我上面提到的,我需要synchronousasynchronous方法,有些客户会调用synchronous方法来获取相同的功能,有些会调用我们的asynchronous方法来获取数据。

所以现在我在想,在同一个客户端代码中实现synchronousasynchronous功能的最佳方法是什么。我知道可能有不同的答案取决于人们如何实现,但作为开发人员,可能有更好的方式来实现它作为我目前的方式。

我还在学习,所以想知道更好的方法,我也可以告诉其他人要解决这些问题,你需要这样做。

现在,我已经创建了一个这样的界面 -

public interface Client {

        // for synchronous
        public String execute(final String userId);

        // for asynchronous
        public Future<String> executeAsync(final String userId);
}

然后我有SmartClient实现上述Client接口。我不确定我是应该这样做还是有更好的方法来实现同步和异步功能。

下面是我的SmartClient代码及其中的其他高级代码,我认为这些代码足以理解整个流程。

public class SmartClient implements Client {

    ExecutorService executor = Executors.newFixedThreadPool(5);

    // This is for synchronous call
    @Override
    public String execute(String userId) {

        String response = null;
        Future<String> future = executor.submit(new Task(userId));

        try {
            response = future.get(3, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            System.out.println("Terminated!");
        }

        return response;
    }

    // This is for asynchronous call
    @Override
    public Future<String> executeAsync(String userId) {

        // not sure what should I do here as well?

    }
}

下面是我将执行实际任务的简单类 -

class Task implements Callable<String> {

    private final String userId;

    public Task(String userId) {
        this.userId = userId;   
    }

    public String call() throws Exception {

        String url = createURL(userId);

        // make a HTTP call to the URL
        RestTemplate restTemplate = new RestTemplate();
        String jsonResponse = restTemplate.getForObject(url , String.class);

        return jsonResponse;
    }

    // create a URL
    private String createURL(String userId) {
        String generateURL = somecode;

        return generateURL;
    }
}

但我正在做一些研究,我发现更好的方法是 -

  

而不是两个方法,一个是同步的,另一个是   异步,有一个描述同步的接口方法   行为。为它编写实现。然后提供一个包装器   包含你的接口实现的类   基本上在提供时调用包装对象的方法   异步行为。

但不知怎的,我无法理解如何实现这一目标?任何人都可以在我的例子中提供一个简单的示例基础,这将有助于我更好地理解如何做到这一点吗?

我或许可以通过这种方式学到新东西。

1 个答案:

答案 0 :(得分:0)

试试这个

@Override
public Future<String> executeAsync(String userId) {
    return executor.submit(new Task(userId));
}
相关问题