JavaSpring,正在等待异步处理程序
为基本问题道歉;我是Java世界和spring框架的新手。我构建了一个小示例应用程序,它向外部服务发出一系列异步请求,并返回一个响应列表(“指标”),但我需要让我的应用程序等待所有响应返回。现在我有一个(不要恨我)线程。在我让结果出来的时候睡觉,但显然这是非常讨厌的。有人能提出更好的架构方法吗 主叫班级:JavaSpring,正在等待异步处理程序,java,spring,asynchronous,Java,Spring,Asynchronous,为基本问题道歉;我是Java世界和spring框架的新手。我构建了一个小示例应用程序,它向外部服务发出一系列异步请求,并返回一个响应列表(“指标”),但我需要让我的应用程序等待所有响应返回。现在我有一个(不要恨我)线程。在我让结果出来的时候睡觉,但显然这是非常讨厌的。有人能提出更好的架构方法吗 主叫班级: @Service public class MetricService { @Autowired private MetricProcessor processor; private Li
@Service
public class MetricService {
@Autowired
private MetricProcessor processor;
private LinkedBlockingQueue<Metric> queue;
@Scheduled(fixedDelay = 60000)
public void queryExternalService() {
List<Metrics> metrics = new ArrayList<>();
metrics = processor.getMetrics();
//this is horrible and I'm a horrible human being
try {
Thread.sleep(10000); //wait for the requests to come back
}
catch (Exception e) {
e.printStackTrace();
}
queue.addAll(metrics);
}
}
@服务
公共类度量服务{
@自动连线
专用计量处理器;
专用LinkedBlockingQueue队列;
@计划(固定延迟=60000)
public void queryExternalService(){
列表度量=新的ArrayList();
metrics=processor.getMetrics();
//这太可怕了,我是个可怕的人
试一试{
Thread.sleep(10000);//等待请求返回
}
捕获(例外e){
e、 printStackTrace();
}
queue.addAll(度量);
}
}
类别:
@Component
public class MetricProcessor {
@Autowired
private AsyncClient externalClient;
public List<Metrics> getMetrics() {
List<Metrics> returnObj = new Arraylist<>();
for(Blah blah : bleh) {
Request request = new Request("abc");
externalClient.getMetricAsync(request, new AsyncHandler<request, result>() {
@Override
public void onError(Exception e) {
System.out.println("Error");
}
@Override
public void onSuccess(Request request, Result result) {
returnObj.add(new Metric(result.getKey(), result.getValue()));
}
});
}
return returnObj;
}
}
@组件
公共类度量处理器{
@自动连线
私有异步客户端外部客户端;
公共列表getMetrics(){
List returnObj=new Arraylist();
为了(诸如此类:诸如此类){
请求=新请求(“abc”);
getMetricAsync(请求,新的AsyncHandler(){
@凌驾
公共无效申报人(例外e){
System.out.println(“错误”);
}
@凌驾
成功时公共无效(请求、结果){
添加(新度量(result.getKey(),result.getValue());
}
});
}
返回OBJ;
}
}
任何帮助都将不胜感激 试试未来的
在MetricService
中:
public void queryExternalService() {
Future<List<Metrics>> metricsFuture = processor.getMetrics();
try {
queue.addAll(metricsFuture.get(60, TimeUnit.SECONDS));
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
}
试试未来的
在MetricService
中:
public void queryExternalService() {
Future<List<Metrics>> metricsFuture = processor.getMetrics();
try {
queue.addAll(metricsFuture.get(60, TimeUnit.SECONDS));
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
}