在我的应用程序中,我希望在写入某些数据的请求到来时立即执行对数据库的任何插入操作。
我正在使用 InnoDB 引擎。
由于插入需要独占锁,因此当当前读取查询有一个共享锁时,其他一些读取可能会再次获得共享锁并且写操作可能不得不等待很长时间。
我希望当队列中有写操作时,没有读操作获得共享锁。一旦在当前写请求之前发起的读操作完成,就应该执行写操作。之后应进行所有其他读取操作。
如何实现?
编辑
由于我使用的是 InnoDB 表并且我没有实现表锁,所以 select 和 insert 之间不应该有冲突。它将被选择和更新。 (如果 select 和 insert 之间也有冲突,请纠正我)
在MySQL中,update的优先级高于select。但是如果有一些读取查询正在执行,那么更新查询会在一些读取查询之后出现。在这种情况下,更新后的读取查询是否会等待更新完成,如此处所述http://dev.mysql.com/doc/refman/5.0/en//table-locking.html或者他们将获得共享锁以及在触发更新查询之前存在的读取查询?
最佳答案
从数据库读取时不需要获取共享锁。事实上,使用默认的事务隔离级别 REPEATABLE READ一个事务中的普通 SELECT
查询从一致的快照中读取。无需获取和要求任何锁,在此事务中您根本看不到其他事务中提交的任何更改。
由于没有获取共享锁,用于更新查询的独占锁会按照它们被归档的顺序立即授予其他 session 。
MySQL 文档说明如下
Consistent read is the default mode in which InnoDB processes SELECT statements in READ COMMITTED and REPEATABLE READ isolation levels. A consistent read does not set any locks on the tables it accesses, and therefore other sessions are free to modify those tables at the same time a consistent read is being performed on the table.
Suppose that you are running in the default REPEATABLE READ isolation level. When you issue a consistent read (that is, an ordinary SELECT statement), InnoDB gives your transaction a timepoint according to which your query sees the database. If another transaction deletes a row and commits after your timepoint was assigned, you do not see the row as having been deleted. Inserts and updates are treated similarly.
关于mysql - 在 MySQL 中如何优先于写入/更新而不是读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14100717/