Ale*_*nko 6 mysql polling blocking wait long-polling
假设我正在编写一个应用程序,我需要从服务器实时获取通知,并且假设这些通知存储在mysql数据库中.为了让我得到它们,我必须继续轮询mysql服务器(不断重复相同的选择查询,直到我真正得到结果)但我认为这是非常无效的方式这样做,因为大多数时候选择会变为空.如果我经常这样做,它在服务器上是不合理的压力,如果我这样做,很少通知会很晚.所以我想知道是否有办法说一个mysql查询阻止,直到匹配条件的结果变得可用.
list = query ("SELECT * FROM `notifications` WHERE `unread`=1") ;
Run Code Online (Sandbox Code Playgroud)
如果没有未读通知,则不会返回空列表,而是等到实际有未读通知返回
我建议使用生产者消费者模式,用新表作为"工作队列"实现.不需要存储过程,因为触发器非常简单.
创建一个包含notification要处理的id 和"处理状态"列的表,例如:
create table work_queue (
id int not null auto_increment,
notification_id int references notifications,
status enum ('ready', 'processing', 'failed')
);
Run Code Online (Sandbox Code Playgroud)
创建一个填充工作队列表的简单触发器:
delimiter $
create trigger producer after insert on notifications
for each row begin
insert into work_queue (notification_id, status)
select new.id, 'ready'
where new.unread;
end; $
delimiter ;
Run Code Online (Sandbox Code Playgroud)
您的代码将具有伪代码:
select * from work_queue where status = 'ready' order by id limit 1update work_queue set status = 'processing' where id = <row.id>notifications where id = <row.notification_id>delete from work_queue where id = <row.id>或update work_queue set status = 'failed' where id = <row.id>(你必须弄清楚如何处理失败的物品)如果您有一个进程轮询,则无需担心锁定问题.如果您有多个进程轮询,则需要处理竞争条件.