项目作者: emqx

项目描述 :
Erlang Connection/Client Pool Library
高级语言: Erlang
项目地址: git://github.com/emqx/ecpool.git
创建时间: 2015-12-30T07:27:55Z
项目社区:https://github.com/emqx/ecpool

开源协议:MIT License

下载


Erlang Connection/Client Pool

ecpool is different with worker-pool libraries in that it is designed to pool connection/clients to server or database.

ecpool tries to avoid the erlang application crash when the server or database going down.

Overview

A pool worker to manage/monitor the connection to server or database:

  1. PoolWorker -> Conn -> DB

Use client:

  1. ecpool:with_client(Pool, fun(Client) -> call(Client) end).

Usage

Start the pool

  1. ecpool:start_pool(Pool, Mod, Opts).

For example:

  1. PgOpts = [%% Pool Size
  2. {pool_size, 10},
  3. %% Pool Type: round_robin | random | hash
  4. {pool_type, round_robin},
  5. %% Auto reconnect
  6. {auto_reconnect, 3},
  7. %% epgsql opts
  8. {host, "localhost"},
  9. {port, 5432},
  10. {username, "feng"},
  11. {password, ""},
  12. {database, "mqtt"},
  13. {encoding, utf8}],
  14. ecpool:start_pool(epgsql_pool, epgsql_pool_client, PgOpts)

The Callback Module

Pool Worker Callback:

  1. -callback connect(ConnOpts :: list()) -> {ok, pid()} | {error, any()}.

For example, epgsql_pool_client module:

  1. -module(epgsql_pool_client).
  2. -behavihour(ecpool_worker).
  3. connect(Opts) ->
  4. Host = proplists:get_value(host, Opts),
  5. Username = proplists:get_value(username, Opts),
  6. Password = proplists:get_value(password, Opts),
  7. epgsql:connect(Host, Username, Password, conn_opts(Opts)).
  8. squery(Pool, Sql) ->
  9. ecpool:with_client(Pool, fun(Client) -> epgsql:squery(Client, Sql) end).

Design

The ecpool supervisor tree:

  1. pool_sup[one_for_all supervisor]
  2. pool[gen-server]
  3. worker_sup[one_for_one supervisor]
  4. worker1 -> connection1
  5. worker2 -> connection1
  6. ....

Author

Feng Lee feng@emqx.io

License

The Apache License Version 2.0