我编写了一个 spring-boot 应用程序,它从用户那里接收一个名为 Calc 的对象,该对象包含两个参数,并返回一个由复杂计算组成的答案(计算本身与问题无关)。因为系统可能很忙,每个对象都进入队列,有一个调度器在队列上按顺序传递,进行计算。
我的问题是如何将项目的计算结果返回给正确的请求。
我已经包含了我写的代码:
Controller :
@RestController
public class CalcController {
@Autowired
private CalculateService calculateService;
@RequestMapping("/")
public int calculate(@RequestBody Calc calc) {
return calculateService.calculate(calc);
}
}
计算对象:
@Data
public class Calc {
private int paramA;
private int paramB;
}
计算服务:
@Service
public class CalculateService {
private BlockingQueue<Calc> calcQueue;
@PostConstruct
private void init() {
calcQueue = new LinkedBlockingDeque<>();
}
public int calculate(Calc calc) {
calcQueue.add(calc);
// TODO: Return calculation result.
return 0;
}
@Scheduled(fixedRate = 2000)
public void calculateQueue() throws InterruptedException {
while (!calcQueue.isEmpty()) {
Calc calc = calcQueue.take();
int result = Calculator.calculate(calc);
// TODO: Return calculation result to the right request.
}
}
}
谢谢
最佳答案
您可以使用 ExecutorService
,它本质上维护一个内部队列以将您的工作请求分派(dispatch)给多个线程。
class Service {
// use 4 threads; optimal is the amount of processor cores available
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(4);
public int calculate(int input) {
Future<Integer> future = EXECUTOR.submit(() -> Calculator.calculate(input));
return future.get(); // this actually thrown an Exception you have to catch
}
}
当执行器有可用线程时,submit
将调用 Calculator.calculate()
,future.get()
将提取该调用的实际结果。
请注意,在计算出结果之前,这段代码确实会阻塞,只有计算本身是并行的。如果您确实想立即返回并稍后提供结果,那就另当别论了,但这并不真正符合 REST Controller 的概念。
您还可以使用 CompletableFuture
简化此代码
class Service {
public int calculate(int input) {
return CompletableFuture.supplyAsync(() -> Calculator.calculate(input)).get();
}
}
关于java - spring boot - 映射对请求的正确响应,用于多异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206175/