cowboy+poolboy+mysqlotp
2、进程池和mysql配置信息放入sys.config
[ {hope, [
{sqlPool, [
{name, mysql},
{poolConf, [
{name, {local, mysql}},
{worker_module, mysql},
{size, 10},
{max_overflow, 5}
]},
{sqlConf, [
{host, "127.0.0.1"},
{port, 3306},
{user, "root"},
{password, "123456"},
{database, "hope"}
]}
]}
]}
].
name 是 子进程ID
poolConf 里面的
name 是 注册名
worker_module 是 启动哪个工作模块
size 启动的进程数
max_overflow 当超过最大进程数时,临时启动的最大进程数(当空闲时,会回收)
3、启动进程池连接数据库
修改hope_sup
init([])->{ok, SqlPool}= application:get_env(hope, sqlPool),
Name = proplists:get_value(name, SqlPool),
PoolArgs = proplists:get_value(poolConf, SqlPool),
WorkerArgs = proplists:get_value(sqlConf, SqlPool),
Mysql = poolboy:child_spec(Name, PoolArgs, WorkerArgs),
{ok,{{one_for_all,5,10},[Mysql]}}.
4、查询数据库代码
新建一个处理sql模块hope_sql
-module(hope_sql).-export([query/1]).
query(Sql)->
poolboy:transaction(mysql,fun(Pid)-> mysql:query(Pid, Sql) end).
5、修改接口数据
-module(hope_main).-export([init/2]).
init(Req0,Opts)->
{ok,FieldList,UserList}= hope_sql:query("select * from user"),
DataList=[lists:zip(FieldList,User)||User<-UserList],
RespBody= jsx:encode([{<<"status">>,<<"ok">>},{<<"data">>,DataList}]),
Req= cowboy_req:reply(200,#{
<<"content-type">>=><<"application/json; charset=utf-8">>
},RespBody,Req0),
{ok,Req,Opts}.
6、rebar3 release
7、./_build/default/rel/hope/bin/hope console
8、看效果
转自: https://www.jianshu.com/p/92394d30a048
以上是 cowboy+poolboy+mysqlotp 的全部内容, 来源链接: utcz.com/z/516636.html