I wrote a spring-boot application that recieves an object named Calc from the user, which contains two parameters, and returns an answer that consists of a complex calculation (the calculation itself is not relevant to the question). Because the system may be busy, each object is entered into the queue, and there is a scheduler that passes by order on the queue, and preforms the calculation.
My problem is how to return the result of the item's calculation to the correct request.
I've included the code I wrote:
controller:
@RestController
public class CalcController {
@Autowired
private CalculateService calculateService;
@RequestMapping("/")
public int calculate(@RequestBody Calc calc) {
return calculateService.calculate(calc);
}
}
Calc Object:
@Data
public class Calc {
private int paramA;
private int paramB;
}
CalculateService:
@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.
}
}
}
Thanks