gpt4 book ai didi

javascript - websockets 和数据库更新(推送更改)

转载 作者:可可西里 更新时间:2023-11-01 07:06:52 24 4
gpt4 key购买 nike

我今天开始学习websockets,因为我想要一个架构,通过它我可以获得实时更新。

我创建了我的第一个 websockets node.js 和 socket.io 应用程序,因此我可以通过 javascript 在客户端和服务器之间进行通信。这很好用。

但我需要一些东西,它可以与 MySQL 进行通信,以便对于某个表上的每个更改,它都必须告诉客户,有一个更改。

所以我在想 node.js 服务器与观察数据库的 PHP 脚本进行通信。但是那时我还需要长时间拉取请求更改,所以无论如何我都可以使用 ajax 来完成,所以它是无用的。

所以我的问题是:我怎样才能从数据库表或某个查询中获取实时数据更改,这会将更新发送到所有实时连接的客户端,而无需长轮询?

谢谢!

最佳答案

So my question: How can I achieve to get real-time data changes from a table of the database or from a certain query...

有一个监视 MySQL 事件的模块:mysql-events

官方示例:

var MySQLEvents = require('mysql-events');
var dsn = {
host: _dbhostname_,
user: _dbusername_,
password: _dbpassword_,
};
var mysqlEventWatcher = MySQLEvents(dsn);
var watcher =mysqlEventWatcher.add(
'myDB.table.field.value',
function (oldRow, newRow, event) {
//row inserted
if (oldRow === null) {
//insert code goes here
}

//row deleted
if (newRow === null) {
//delete code goes here
}

//row updated
if (oldRow !== null && newRow !== null) {
//update code goes here
}

//detailed event information
//console.log(event)
},
'match this string or regex'
);

... which will send the update to all clients, that are connected in real-time, without long polling?

您可以使用 socket.io并通过在客户端执行此操作来完全阻止初始的 http 轮询:

var socket = io({transports: ['websocket'], upgrade: false});

为避免客户端使用轮询,将此行添加到服务器:

io.set('transports', ['websocket']);

并将事件从 mysql-event 发送到所有连接的 (socket.io) 客户端,使用以下命令:

io.sockets.emit('db-event',eventDataObj)

关于javascript - websockets 和数据库更新(推送更改),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45550177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com