脚本参考地址:https://github.com/DawnAngel/lua-nats/tree/master/examples
lua subscribe.lua
package.path = '../src/?.lua;src/?.lua;' .. package.path
pcall(require, 'luarocks.require')
local nats = require 'nats'
local params = {
host = '127.0.0.1',
port = 4222,
}
local client = nats.connect(params)
local function subscribe_callback(payload)
print('Received data: ' .. payload)
end
-- client:enable_trace()
client:connect()
local subscribe_id = client:subscribe('foo', subscribe_callback)
client:wait(2)
client:unsubscribe(subscribe_id)
publish.lua
package.path = '../src/?.lua;src/?.lua;' .. package.path
pcall(require, 'luarocks.require')
local nats = require 'nats'
local params = {
host = '127.0.0.1',
port = 4222,
}
local client = nats.connect(params)
-- client:enable_trace()
client:connect()
client:publish('foo', 'bar A')
client:publish('foo', 'bar B')
1.linux安装lua5.3
参考菜鸟教程:https://www.runoob.com/lua/lua-environment.html
curl -R -O http://www.lua.org/ftp/lua-5.3.0.tar.gz
tar zxf lua-5.3.0.tar.gz
cd lua-5.3.0
make linux test
make install
2.lua publish.lua脚本执行
先看下lua nats_pub脚本
直接执行lua publish.lua 报错 lua: ../src/nats.lua:10: module 'cjson' not found
查看nats.lua代码发现缺少cjson,uuid,sockert
2.安装cjson
wget https://www.kyne.com.au/~mark/software/download/lua-cjson-2.1.0.zip
unzip lua-cjson-2.1.0.zip
cd cd lua-cjson-2.1.0
修改Makefile文件
PREFIX = /usr/local
LUA_CMODULE_DIR = $(PREFIX)/lib/lua/5.3
"/usr/local"是安装lua5.3中的Makefile配置INSTALL_TOP= /usr/local
3.使用luarocks安装uuid和socket
http://luarocks.org/releases/luarocks-2.1.0.tar.gz
tar zxpf luarocks-3.3.1.tar.gz
/usr/local/bin/luarocks install uuid
/usr/local/bin/luarocks install socket
4.执行lua subscribe.lua 和publish.lua成功发送和接收消息
lua publish.lua
lua subscribe.lua
Received data: bar A
Received data: bar B
网友评论