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