doujiao1180 2019-06-28 09:05
浏览 460
已采纳

并发安全访问golang中的数据库

i'm need some recomendation about concurrency work database golang. For example, i've database with payment info. How could i get actual inforamtion about payments, if it have more than 1 connection which all time update database?

I'm tried to use transaction with gorm but i'm not sure its work or not. Also i'm trying to use mutex, but if my app has more than 1 instance it doesn't work correctly. Also i'm trying to use sql like Update payment set someinfo = someinfo || " addition info" where some condition.

  • 写回答

1条回答 默认 最新

  • duanfu7994 2019-06-28 13:39
    关注

    There are two components to consider with this:

    Thread-safety of go language client

    The first one requires auditing, hopefully it is easy to find this information through the community without having to drop down into code level audits. I see that concurrent (thread) safety is mentioned for a number of the abstractions on the official go documentation so it should be easy to find which structs and methods are safe for concurrent use from a language level perspective (go).

    Database Transaction Isolation Levels

    The second is consideration starts to get into database and the guarantees that your specific DB offers (and just general distributed systems fun :) ) The default isolation level for postgres/mysql allow for 2 concurrent reads to see the same data, and then have each one overwrite the other (on a write). The postgres documentation provides an excellent example of this case:

    Because of the above rule, it is possible for an updating command to see an inconsistent snapshot: it can see the effects of concurrent updating commands on the same rows it is trying to update, but it does not see effects of those commands on other rows in the database. This behavior makes Read Committed mode unsuitable for commands that involve complex search conditions; however, it is just right for simpler cases. For example, consider updating bank balances with transactions like:

    BEGIN;
    UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 12345;
    UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 7534;
    COMMIT;
    

    If two such transactions concurrently try to change the balance of account 12345, we clearly want the second transaction to start with the updated version of the account's row. Because each command is affecting only a predetermined row, letting it see the updated version of the row does not create any troublesome inconsistency.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败