不断刷新数据库中的数据



我有这个Spring VMC表,我想显示:

@Controller
public class FileImportsController {
private EntityImportRequestsService entityImportRequestsService;
@Autowired
public FileImportsController(EntityImportRequestsService entityImportRequestsService) {
this.entityImportRequestsService = entityImportRequestsService;
}
@GetMapping("/imported_files")
public String viewHomePage(Model model) {
List<EntityImportRequestsTable> listProducts = entityImportRequestsService.findAll();
model.addAttribute("listProducts", listProducts);
return "index";
}
}

页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Product Manager</title>
</head>
<body>
<div align="center">
<h1>Product List</h1>
<table border="1" cellpadding="10">
<thead>
<tr>
<th>Product ID</th>
<th>Name</th>
<th>Brand</th>
<th>Made In</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr th:each="product : ${listProducts}">
<td th:text="${product.requestId}">Product ID</td>
<td th:text="${product.name}">Name</td>
<td th:text="${product.brand}">Brand</td>
<td th:text="${product.madein}">Made in</td>
<td th:text="${product.price}">Price</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

如何每5秒拉数据库表数据并刷新表数据?

虽然你仍然可以使用javascript setInterval函数来调用api,像这样:

setInterval(function() {
$.ajax({
url: 'http://yourserver.com/getproductlist',
type: 'GET',
success: function(data) {
// your code to refresh the table here
}
});
}, 5000);

遗嘱:

  1. 服务器超载,想象一下每5秒刷新数千人。
  2. 显示旧数据的风险:数据将过期5秒(示例产品可能缺货)。

一个更好的选择是使用websocket和消息传递的实时解决方案,如RabbitMQ:

当数据库中的数据发生变化时,RabbitMQ会向客户端发送更新(触发器可以提供帮助)。这样,客户机只在有新数据时接收更新,而不是不断地轮询服务器以获取更新。如果您在azure中托管解决方案,您可以使用azure存储队列或服务总线,在AWS中您可以使用SQS。这里有一个类似的问题:使用JSF/Java EE实时更新数据库

在HTML的head元素中使用meta标签,如下所示:https://www.geeksforgeeks.org/how-to-automatic-refresh-a-web-page-in-fixed-time/

您没有说明您的具体要求是什么。数据真的每5秒就改变一次吗?或者你不想错过任何更新?

要刷新你的网页,请使用head标签:

<head>
<title>Product Manager</title>
<meta charset="utf-8"/>
  <meta http-equiv="refresh" content="5">
</head>

但如果数据只是不时变化,我会使用push(而不是pull)。

例如HTML5 server-sent-events:https://www.w3schools.com/html/html5_serversentevents.asp

您可以每5秒用一个spring引导调度器查询一次db表,或者您可以在数据更改时在服务器端使用消息传递。(我更喜欢。这可以减少CPU负载和带宽,并且更具可持续性。

创建一个休眠5秒的while循环,然后从数据库中获取数据并更新DOM。

我认为你要做的,是不可能没有一个不同的架构,因为你这里有一个服务器端渲染页面不使用websockets或类似的东西。

在"现代世界"中,你会有一个Websocket客户端连接到你的后端,当你的数据库表发生变化时,它会实时得到通知。(不管你知道数据改变的反应方式,还是使用"原始轮询"到你的数据库表);在你的后端,然后在websocket上推送更改)

但是如果你想让它保持现在的样子,我认为只有两个选择:

  1. 尝试一些AJAX,定期更新这个DOM元素
  2. 每X秒用JavaScript刷新页面,这反过来会重新加载数据,通过再次执行Rest API调用

最新更新