java - 如果在 Spring Boot 中同时出现多个请求,如何保持?
问题描述
我正在使用 Spring Boot,我的应用程序基于Date 和 Time工作。问题是,如果一个请求来自 jsp 页面,我必须循环来自 jsp 页面的 json 对象并将这些值保存在 db 中。对于一个请求, table 中将有6 个插入。因此,如果有 n 个请求,则n*6插入。
但是,如果所有请求同时出现(在特定时间甚至毫秒是相同的),我需要的是,请求之间应该有时间实验室(至少以毫秒为单位)。现在,如果多个请求同时出现,它不会显示任何时间间隔。Spring Boot 使用线程。我尝试使用“单例”。但它不起作用。我不擅长单例设计,但我参考了一些教程。我使用递归函数为每个请求创建新时间。
- 单例:只创建一个实例(默认范围)
- 原型:每次引用原型 bean 时都会创建新实例。
- 请求:单个 HTTP 请求的一个实例。
- session:一个 HTTP Session 实例
控制器类
@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 个请求后保存。
推荐阅读
- c# - 在 listview winform c# 中列出 S3 Bucket 键
- javascript - 在下拉列表中的 0 索引上插入值
- java - OnTouchListener webview 总是循环
- javascript - React-Native Javascript 搜索过滤功能
- python - 如何在数据框中纠正拼写错误的单词?
- r - 以最小距离连接矩阵的两个坐标
- visual-studio-code - VSCode,Intellisense C++ 自动完成功能不起作用,ubuntu 20.04
- wordpress - WooCommerce 如果订单状态正在处理,则该特定订单中的产品将从商店隐藏
- python - pygetwindow 模块是做什么用的?
- javascript - CSS:创建流程步骤样式