Create a notification server using MySql/ Node js

北城余情 提交于 2021-02-05 09:49:01

问题


I am working on a project where I should post notification whenever an database event is fired.

I am using NODE for this. BUt I am not sure whether I'll be able to do it or not.

I came across this question On SO but It didn't help much.

I also saw NODE.js MySql Connectors

What my Real questions are:

1) Is there anything like reading MySql triggers in Node js. ? Can I push instant notification as soon as a row is entered in the desired table?

2) If Yes, How should I go about it?

3) If it is not possible and I have to check the DB changes manually after every few seconds, Why should I use Node.js instead of making asynchronous calls from browser after every few seconds using jQuery?

Any help would be appriciated...!


回答1:


As for as I know, there isn't any simple way to read database triggers in Node, so a common solution is to use Redis as a publish system, and have a connector module perferm the actual database query. A very popular MySQL connector for Node is this one, so I will be using it as an example.

When using a module, the "MySQL triggers" you're looking for are just simple callbacks that you would find with most asynchronous modules. Here's an example of a query with the node-mysql module:

var post  = {id: 1, title: 'Hello MySQL'};
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //the database transaction has completed, notify the client
});

When the callback is called, that means the database operation has either completed, or failed (check the err property in the callback to check this). You could then send this change to a browser using EventSource/Server-Sent Events or WebSockets.

As a side answer to your third question, pushing data from the server to client will always be more efficient than the client consistently asking for data, because the server is not guaranteed to have need data when the client has asked for it.



来源:https://stackoverflow.com/questions/18576013/create-a-notification-server-using-mysql-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!