优化mysql / JS / php聊天

时间:2016-08-30 21:40:21

标签: javascript php mysql optimization chat

我做了这个javascript / php / mysql,2个用户,聊天。它每3秒请求(ajax)带有消息的php文件并更新页面。 php使用以下命令查询数据库:

SELECT * FROM tmessagges WHERE author='Jack' OR author='John'

我能优化吗?

我认为要优化的第一件事就是当没有新的消息时浪费了所有的请求,但我不确定是否值得... 可能只是选择id或count,并且仅在有新的消息时才发出第二个请求。

SELECT id FROM tmessagges WHERE author='Jack' OR author='John'

SELECT COUNT(id) FROM tmessagges WHERE author='Jack' OR author='John'

然后是第一个查询,如果是新的消息。

值得吗?我认为cpu的使用率大致相同,只是流量较少......

或其他优化方法?

1 个答案:

答案 0 :(得分:1)

有一个与每条消息相关联的序列号,然后只询问“晚于”该消息的消息。

只有一个“名字”可供查找 - 也许是“消息ID”,而不是“杰克”或“约翰”。

现在查询更短:

if(isEvent)
{
    //Populate using Event collection
    Inquiry.find({_id : someID}).
            populate({path : 'data' , model : Event}).
            exec(function(err,docs){...});
}
else if(isProperty)
{
    //Populate using Property collection
    Inquiry.find({_id : someID}).
            populate({path : 'data' , model : Property}).
            exec(function(err,docs){...});
}

除了某种“空洞”的回复之外,通常都会返回。当有消息时,它将仅返回新消息,而不是其余的消息。

此外,不要通过网络发送SQL。而是拥有某种最小化流量的协议,例如

var SerialPort = require("serialport")
var serialPort = new SerialPort('/dev/ttyACM0', 
{   baudrate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
});

serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) { // 아두이노로부터 전달된 데이터
    console.log('data received: ' + data);
});

serialPort.write("Hello from Raspberry Pi\n", function(err, results) {
    console.log('err ' + err);
    console.log('results ' + results); //전송한 바이트 수
});

setInterval( 
function() { // 2초마다 아두이노에게 문자열을 전송하는 예
   serialPort.write('hello');
}, 2000);
});