Postgres Advisory Locks

问题

Postgres的select ... for update可以锁住一行,但是想找一个可以带上purpose的锁住一行,purpose不同可以获得不同的锁。

方案

然而并没有,但找到一个AdvisoryLocks
AdvisoryLocks可以根据不同的key,获得不同的锁。但是AdvisoryLocks的key只能是一个bigint或者两个int,不能传入字符串,就不能很明确的锁住一行。
Google了一下,大专栏  Postgres Advisory Locks3845/how-do-i-use-string-as-a-key-to-postgresql-advisory-lock" target="_blank" rel="external noopener noreferrer">这篇文章提供了一种解决方案select pg_advisory_lock( hashtext('fredfred') );

相关

Ruby还有一个相关的gem with_advisory_lock,该gem也支持字符串作为key,查看了一下源码:
Zlib.crc32(input.to_s)
使用crc将字符串转换成了数字。

总结

不管哪种方法,都有一个缺陷,不能做到string映射int的唯一性

猜你喜欢

转载自www.cnblogs.com/dajunjun/p/11717954.html