1、首先添加依赖,启动项
{deps, [
jsx,
{poolboy, {git, "https://github.com/devinus/poolboy.git", {tag, "1.5.2"}}},
{mysql, {git, "https://github.com/mysql-otp/mysql-otp.git", {tag, "1.4.0"}}},
{cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.6.1"}}}
]}.
{relx, [{release, {hope, "1.0.0"},
[jsx,poolboy,mysql,cowlib,ranch,cowboy,
hope,
sasl]},
{sys_config, "./config/sys.config"},
{vm_args, "./config/vm.args"},
{dev_mode, true},
{include_erts, false},
{extended_start_script, true}]
}.
jsx 是用来json编解码
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}.