因此,当我访问enpoint(POST请求)时,我首先检查数据库中是否已存在条目。如果是,我想将其返回给用户(出于跟踪目的)并继续操作。但我想将ID返回给用户并继续此过程。如何实现这一目标?
@RestController
public class StudentController {
@Autowired
private StudentService service;
@PostMapping("/storeInDB")
@ResponseBody
public File_Tracking saveStudentDetails(@RequestBody Student student ) throws IOException {
List<Students> student = new ArrayList<>();
int continue = 0;
int id = 0;
id = service.getId(); // I want to return this and continue some other process which follows
答案 0 :(得分:3)
您可以在另一个线程中异步运行进程 ,而您的主线程将id作为服务响应返回。
查看此博客,了解如何使用spring @Async批注定义Async操作 https://www.baeldung.com/spring-async
答案 1 :(得分:1)
除了Sandeep Lakdawala的答案外,由于这两个操作应该互相遵循(应先将 id 返回给用户,然后该操作应该很顺利),因此您应该考虑安排不同的线程。通常,计算机会随机给线程分配时钟时间。
例如,如果我们有线程t1和线程t2,并且这些t1在控制台上显示“嘿”,而t2则显示“哇!”控制台,启动程序时,您会在控制台中看到以下内容之一:
嘿,嘿,哇!哇!
或
哇!嘿,哇!哇!
因此,为了实现您的目标,您应该搜索线程同步。另外,您可以访问站点“ https://www.baeldung.com/java-thread-safety”,以了解Java中线程的同步。
此外,在完成此任务之前,我建议您阅读有关线程和进程的信息,因为它们是计算机科学中非常重要的主题。 “ What is the difference between a process and a thread?”将是一个很好的起点。