Home  >  Q&A  >  body text

java - get_lock(str,timeout)函数使用。

在DB层面实现分布式锁的方法有:利用MySQL的内置函数 get_lock(key, timeout)来实现,这个函数的约定在指定时间内持有锁,它锁的是一行中的某一个字段么?还是锁的是一行?具体项目中是如何使用的?查了一些资料,大概是先约定同一个key,然后先执行get_lock(key,timeout)的,会持有锁,其他的sql只能等待;除非当前的线程释放锁release(key),但是它是如何在项目中控制锁的粒度呢?最好有实例能详解一下。谢谢~~

怪我咯怪我咯2764 days ago418

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:45:21

    This lock is application level and used between different mysql sessions. It is just a name lock, and has no direct relationship with the tables, rows, and fields you understand. The specific lock is completely left to the application. It is an exclusive lock, which means that whichever session holds the lock, other sessions will fail when trying to get the lock.

    For example, if you want to lock a row of record A, then you create a lock in the current sessionget_lock("record A", 10)。此时其他所有会话依然可以随便访问和修改record A,除非他们显式的也调用get_lock("record A", 10).

    That is to say, it is entirely up to your application to decide whether to check the lock or not. If you want to lock, make all sessions explicitly call get_lock("record A", 10),那明显只有一个会话能成功。其他会话只有等超时或者持有锁的会话调用release_lock when accessing record A before you can get the lock again

    Similarly, if you want to lock a field column A, then create a lock as aboveget_lock("column A", 10). In short, it is up to the application to decide whether to take the lock or not, and the database only provides this mechanism. To see if everyone grabs the same lock, it is purely based on the fact that the string of the first parameter lock name is different, so the best practice is to add the table name and database name in front of the lock name to avoid accidental injuries

    reply
    0
  • Cancelreply