0

是否有与以下 asynch/await .NET 4.5 代码等效的 Java 代码来处理 httprequests 或任何调用的方法调用)?

public async Task<System.IO.TextReader> DoRequestAsync(string url)
{
    HttpWebRequest req = HttpWebRequest.CreateHttp(url);
    req.AllowReadStreamBuffering = true;
    var tr = await DoRequestAsync(req);  // <- Wait here and even do some work if you want.
    doWorkWhilewaiting();                // ...look ma' no callbacks.
    return tr;
}

我计划在控制器 /GET 方法中调用它(从第 3 方 REST 端点获取数据),我对 java 世界完全陌生。

非常感谢任何信息。

4

2 回答 2

3

不,Java 没有像 async/await 这样的东西。该java.util.concurrent包包含各种有关并发的有用类(用于线程池、生产者/消费者队列等),但实际上是 C# 5 中的语言支持将所有内容联系在一起......而这在 Java 中还不存在。

据我所知,它也不是 Java 8 计划的一部分——尽管方法字面量和 lambda 表达式之类的东西至少会使显式回调方法比 Java 7 中的方法简单得多。

于 2013-06-27T05:49:57.843 回答
0

我最近发布了一个 apt 库JAsync。它实现了 Async-Await 模式,就像 Java 中的 es 一样。它使用 Reactor 作为其低级实现。它现在处于 alpha 阶段。有了它,我们可以编写如下代码:

@RestController
@RequestMapping("/employees")
public class MyRestController {
    @Inject
    private EmployeeRepository employeeRepository;
    @Inject
    private SalaryRepository salaryRepository;

    // The standard JAsync async method must be annotated with the Async annotation, and return a JPromise object.
    @Async()
    private JPromise<Double> _getEmployeeTotalSalaryByDepartment(String department) {
        double money = 0.0;
        // A Mono object can be transformed to the JPromise object. So we get a Mono object first.
        Mono<List<Employee>> empsMono = employeeRepository.findEmployeeByDepartment(department);
        // Transformed the Mono object to the JPromise object.
        JPromise<List<Employee>> empsPromise = Promises.from(empsMono);
        // Use await just like es and c# to get the value of the JPromise without blocking the current thread.
        for (Employee employee : empsPromise.await()) {
            // The method findSalaryByEmployee also return a Mono object. We transform it to the JPromise just like above. And then await to get the result.
            Salary salary = Promises.from(salaryRepository.findSalaryByEmployee(employee.id)).await();
            money += salary.total;
        }
        // The async method must return a JPromise object, so we use just method to wrap the result to a JPromise.
        return JAsync.just(money);
    }

    // This is a normal webflux method.
    @GetMapping("/{department}/salary")
    public Mono<Double> getEmployeeTotalSalaryByDepartment(@PathVariable String department) { 
        // Use unwrap method to transform the JPromise object back to the Mono object.
        return _getEmployeeTotalSalaryByDepartment(department).unwrap(Mono.class);
    }
}
于 2021-09-15T02:17:28.277 回答