时间:2021-07-01 10:21:17 帮助过:85人阅读
mysql模拟队列
Java代码
-- 初始化数据
DROP TABLE IF EXISTS t_msg_queues;
CREATE TABLE t_msg_queues(
msg_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
msg_content VARCHAR(255) NOT NULL,
owner_thread_id INT NOT NULL DEFAULT -1,
PRIMARY KEY (msg_id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
SET @maxRandom = POWER(10,6);
INSERT INTO `t_msg_queues`(`msg_content`)
VALUES (CONCAT("cont_",CEIL(RAND()*@maxRandom))),(CONCAT("cont_",CEIL(RAND()*@maxRandom)))
,(CONCAT("cont_",CEIL(RAND()*@maxRandom))),(CONCAT("cont_",CEIL(RAND()*@maxRandom)))
,(CONCAT("cont_",CEIL(RAND()*@maxRandom))),(CONCAT("cont_",CEIL(RAND()*@maxRandom)))
,(CONCAT("cont_",CEIL(RAND()*@maxRandom))),(CONCAT("cont_",CEIL(RAND()*@maxRandom)))
,(CONCAT("cont_",CEIL(RAND()*@maxRandom))),(CONCAT("cont_",CEIL(RAND()*@maxRandom)))
,(CONCAT("cont_",CEIL(RAND()*@maxRandom))),(CONCAT("cont_",CEIL(RAND()*@maxRandom)));
-- 获取1条未处理的消息
SET SESSION autocommit=1;
SET @msgID = -1;
UPDATE t_msg_queues SET owner_thread_id=GREATEST(CONNECTION_ID() ,(@msgID:=msg_id)*0)
WHERE owner_thread_id=-1 ORDER BY msg_id LIMIT 1;
-- 此时@msgID如果为-1,代表没有待处理的消息,否则就代表本次需要处理的msg_id
bitsCN.com