【发布时间】:2018-07-09 10:16:25
【问题描述】:
我正在使用 Spring Boot,我的应用程序基于 日期和时间 运行。问题是,如果一个请求来自 jsp 页面,我必须循环来自 jsp 页面的 json 对象并将这些值保存在 db 中。对于一个请求,表中将有 6 个插入。因此,如果有 n 个请求,则 n*6 插入。
但如果所有请求同时出现(在特定时间甚至毫秒都相同),我需要的是,应该有 时间实验室 请求之间(至少以毫秒为单位)。现在,如果多个请求同时出现,它不会显示任何时间间隔。 Spring Boot 使用线程。我尝试使用“单例”。但它不起作用。我不擅长单例设计,但我参考了一些教程。我使用递归函数为每个请求创建新时间。
- 单例:只创建一个实例(默认范围)
- prototype:每次引用原型 bean 时都会创建新实例。
- 请求:单个 HTTP 请求的一个实例。
- 会话:HTTP 会话的一个实例
控制器类
@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 个插入(第二个请求)在时间上相同但与第一个不同。
总结:保留所有请求,直到一个请求保存在数据库中。
如果我的方法有误,请告诉我任何其他方法。
【问题讨论】:
-
你为什么需要它?用于处理请求的线程池已经限制传入请求。除非您想按传入顺序处理您的请求
-
@varman 你为什么不在数据库端处理这个使用隔离和传播的事务。锁定表或行,然后为下一个请求处理新事务。
-
@MạnhQuyếtNguyễn 我需要它来处理不同的 sql 命令
-
@mallikarjun 我刚刚看了一些教程,
@Transactional(propagation=Propagation.REQUIRES_NEW)可以帮我吗? -
@varman google 和 here 简单的开始。
标签: java spring spring-mvc spring-boot singleton