处理过程分为三个步骤:数据库
一、从数据库查询一条状态为为用的记录(不一样的数据库写法会不同)服务器
select * from table1 where state = '未用' limit 1ui
二、将数据状态更新为已用,若是更新成功(影响记录数为1表示成功)则表示获取数据成功,不然这条数据已经被其余服务器或线程所抢用。线程
update table1 set state = '已用' where id='数据id' state = '未用';it
三、使用数据,若是未正常使用数据可将数据状态还原为未用table
上面这个方法存在一个缺陷,假如获取数据后本服务器挂掉,会致使数据未正常处理,能够考虑另一个方法处理:增长一个用于记录数据获取的表table2(table1_id(主键),guid(用于惟一标识获取数据放),expired(过时时间))gui
一、从数据库查询一条状态为为用的记录,不一样的数据库写法会不同date
delete from table2 where expired <= '当前时间';(先删除过时的记录,可能获取方已挂掉)select
select * from table1 where state = '未用' and not exists(select * from table2 where table1_id = table1.id) limit 1;方法
二、在table2插入一条数据表名本方已获取数据,若是插入成功(影响记录数为1,没有抛出主键冲突的异常)则表示获取数据成功,不然这条数据已经被其余服务器或线程所抢用。
insert into table2 (...) values (记录的id,本方的惟一标识,当前时间+一个合理的值做为过时时间);
三、使用数据,若是正常使用数据则将数据状态更新为已用,并删除table2的记录
update table1 set state = '已用' where id='数据id' state = '未用';
delete from table2 where id=[id];