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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?