dousong3760 2014-10-22 08:59
浏览 14
已采纳

编写连接池

How can I write a connection for example for database. The awesome package Redis provide the type pool for cache redis database connections.

How can I write this kind of connection pool, that caches database connections?

  • 写回答

1条回答 默认 最新

  • dongsuiying7773 2014-10-22 09:41
    关注

    These are the exported fields of redis.Pool:

    type Pool struct {
        Dial         func() (Conn, error)
        TestOnBorrow func(c Conn, t time.Time) error
        MaxIdle      int
        MaxActive    int
        IdleTimeout  time.Duration
    }
    
    • Dial is needed to create new connections on-demand. That is, when the pool has lended all its connections out and a new connection is requested from it.
    • TestOnBorrow will check a connection's health before it is lended to a user. If it returns an error, a new connection will be created (using Dial) and the old connection will be closed/discarded.
    • MaxIdle is the amount of not-lended connections which are contained in the pool. A pool will not create any new connections (through Dial) if it has this many connections.
    • MaxActive is the amount of total connections that the pool will ever manage at any given time. Lended plus not-lended connections.
    • IdleTimeout is a duration after which a connection that has been sitting in the pool unlended will be closed and a new one opened in it's stead.

    I use the word "lending" instead of "borrowing" because the direction in which data flows (who's providing and who's consuming) is clearer.

    To implement such a pool you also need to wrap your connections (as the redis package does) to return them to the pool when a user calls Close() on them. Additionally, a read/write timestamp is kept on each connection in order to provide the idle-timeout functionality.

    In order to be concurrently usable, you also need to provide access-locking and atomic counting of connections so that you can never surpass the maximum amount of idle/active connections.

    The actual set of connections managed by a redis connection pool is kept in a list.List structure in the Pool's idle field.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?