无法让 CompletableFuture 和 Spring REST 一起工作
Can't get CompletableFuture and Spring REST to work together
我一直在尝试为用户登录制作一个简单的后端。
如果我不使用线程,它工作正常,但是当我尝试实现多线程时,由于某种原因它中断了。
目前,我只是想做一些简单的事情,例如以 JSON 格式从用户 table 检索所有用户的信息。问题是 Rest 控制器 returns 对 Postman 没有任何作用,即使 dbActions.getAll()
returns 是正确的列表。
没有错误,没有异常,什么都没有。我真的需要一些帮助。我试图开始工作的代码部分如下。
休息控制器:
@Async
@RequestMapping(value="/view", method =RequestMethod.GET)
public List<User> viewAll() {
try {
List<User> list = new ArrayList<>();
list = dbActions.getAll();
return list;
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
dbActions 服务:
public List<User> getAll() {
List<User> results = new ArrayList<>();
CompletableFuture<Void> future;
try {
future = CompletableFuture.runAsync(new Runnable() {
public void run() {
userRepo.findAll().forEach(results::add);
}
});
future.get();
return results;
} catch (Exception e) {
e.printStackTrace();
return results;
}
}
尝试从您的 viewAll()
方法中删除 @Async
注释
我一直在尝试为用户登录制作一个简单的后端。
如果我不使用线程,它工作正常,但是当我尝试实现多线程时,由于某种原因它中断了。
目前,我只是想做一些简单的事情,例如以 JSON 格式从用户 table 检索所有用户的信息。问题是 Rest 控制器 returns 对 Postman 没有任何作用,即使 dbActions.getAll()
returns 是正确的列表。
没有错误,没有异常,什么都没有。我真的需要一些帮助。我试图开始工作的代码部分如下。
休息控制器:
@Async
@RequestMapping(value="/view", method =RequestMethod.GET)
public List<User> viewAll() {
try {
List<User> list = new ArrayList<>();
list = dbActions.getAll();
return list;
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
dbActions 服务:
public List<User> getAll() {
List<User> results = new ArrayList<>();
CompletableFuture<Void> future;
try {
future = CompletableFuture.runAsync(new Runnable() {
public void run() {
userRepo.findAll().forEach(results::add);
}
});
future.get();
return results;
} catch (Exception e) {
e.printStackTrace();
return results;
}
}
尝试从您的 viewAll()
方法中删除 @Async
注释