写在前面
skynet 服务之间有自己的一套高效通信 API 。本文给出简单的示例。
文章目录
- 写在前面
- 准备工作
- 编写代码
- 运行结果
准备工作
首先要有一个编译好,而且工作正常的 skynet 。
编写代码
在 skynet/example 目录编写一个配置文件,两个代码文件。
calc.lua
提供数值计算服务。
local skynet = require "skynet"local CALC = {}-- 处理加法
function CALC.add(...)local res = 0for i, v in ipairs{...} dores = res + vendreturn res
end-- 处理减法
function CALC.sub(lhs, rhs)return lhs - rhs
end-- 处理 lua 消息
function lua_handle(session, source, cmd, ...)local f = assert(CALC[cmd])skynet.ret(skynet.pack(f(...)))
endfunction task()-- 注册 lua 消息的处理函数skynet.dispatch("lua", lua_handle)
endskynet.start(task)
主服务 main_test
负责启动 calc ,之后周期发出数值计算请求。
local skynet = require "skynet"local calc_serv = nil-- 初始化函数
function init()math.randomseed(math.floor(skynet.time()))calc_serv = skynet.newservice("calc")
end-- 服务函数
function task()while true do-- 加法local a = math.random(1, 100)local b = math.random(1, 100)local c = math.random(1, 100)local ret = skynet.call(calc_serv, "lua", "add", a, b, c)skynet.error(a .. " + " .. b .. " + " .. c .. " = " .. ret)-- 睡眠三秒skynet.sleep(300)-- 减法local lhs = math.random(1, 100)local rhs = math.random(1, 100)local ret = skynet.call(calc_serv, "lua", "sub", lhs, rhs)skynet.error(lhs .. " - " .. rhs .. " = " .. ret)-- 睡眠三秒skynet.sleep(300)end
end-- 注册初始化函数
skynet.init(init)-- 启动服务
skynet.start(task)
配置文件 config_test
-- 启动多少个工作线程
thread = 8-- skynet 工作在单节点模式下
harbor = 0-- skynet 节点的主程序
start = "main_test"-- lua 服务代码所在的位置
luaservice = "./service/?.lua;./examples/?.lua"
运行结果
root@macbook:~/skynet# ./skynet examples/config_test
[:00000001] LAUNCH logger
[:00000002] LAUNCH snlua bootstrap
[:00000003] LAUNCH snlua launcher
[:00000004] LAUNCH snlua cdummy
[:00000005] LAUNCH harbor 0 4
[:00000006] LAUNCH snlua datacenterd
[:00000007] LAUNCH snlua service_mgr
[:00000008] LAUNCH snlua main_test
[:00000009] LAUNCH snlua calc
[:00000008] 52 + 77 + 75 = 204
[:00000008] 25 - 56 = -31
...