我正在使用 Spring Boot,我的应用程序基于日期和时间运行。问题是,如果一个请求来自 jsp 页面,我必须循环来自 jsp 页面的 json 对象并将这些值保存在 db 中。对于一个请求,表中将有 6 次插入。因此,如果有 n 个请求,则插入 n*6 个。
但是,如果所有请求同时出现(特定时间甚至毫秒都是相同的),我需要的是,应该有时间实验室 请求之间(至少以毫秒为单位)。现在,如果多个请求同时出现,它不会显示任何时间间隙。 Spring Boot 使用线程。我尝试使用“单例”。但这不起作用。我不擅长单例设计,但我引用了一些教程。我使用递归函数为每个请求创建新时间。
- singleton: only one instance is created (default scope)
- prototype: new instance is created everytime prototype bean is referenced.
- request: one instance for a single HTTP request.
- session: one instance for an HTTP Session
Controller 类
@RequestMapping(value = "/save", method = RequestMethod.GET)
public String saveCategory(@ModelAttribute("gaugeForm") Gauge gauge, @RequestParam(value = "values") String json)
{
//makeing json to List using ObjectMapper
LocalDateTime now = LocalDateTime.now();
String nowDateTime =checkDateTime(now.toString()); // checking and getting if the date and time already exists in db using recursive function.
//A simple example what I do.
for (int i = 0; i < list.size(); i++) {
gauge.setName(i);
gauge.setDatetime(nowDateTime ) // now dateTime
gaugeService.saveOrUpdate(gauge);
}
}
实体类
@Entity
@Table(name = "gauge")
@Proxy(lazy = false)
@Scope(value = "singleton") // try to create an instance at a time
public class Gauge {
private String name;
private String datetime;
//constructors, gettters and setters
}
递归函数
public String checkDateTime(String dateTime) {
if (gaugeService.isDateTimeInDB(dateTime)) {
LocalDateTime now = LocalDateTime.now();
return checkDateTime(now.toString());
} else {
return dateTime;
}
}
下图显示了我到底需要什么。前 6 个插入(第一个请求)在时间上相同,接下来的 6 个插入(第二个请求)在时间上相同但与第一个不同。
摘要:保留所有请求,直到一个请求保存在数据库中。
如果我的方法不对,请告诉我任何其他方法。
最佳答案
您可以在客户端添加一个唯一的 uuid 并将其传递到这 6 个请求中,在服务器端您可以通过 uuid 键将它们放入映射中,并在收到所有 6 个请求后保存。
关于java - Spring Boot中如果同时出现多个请求,如何保持多个请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243133/