doujiao1180 2019-06-28 01: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 05: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部