skynet + redis 发布订阅 多频道开启关闭管理以及监听

local skynet = require("skynet")
local redis = require("skynet.db.redis") 
local sconfig = util.get_server_config() --- 自己的redis配置
local util = require("util")
require("skynet.manager")

local CMD = {}
local channels = {}
local channelFunction = {} ---开启频道的方法table

function CMD.open_cross_channel(channelName) --- 开启频道
	cross_chat_function(channelName)
end

function cross_chat_function(channelName) --- 开启频道的方法 每开一个都要以方法的形式放入table
	
	channelFunction[channelName] =  
	function(channelName)
		local channelwatching = redis.watch(sconfig.redis)
		channels[channelName] = channelwatching
		channelwatching:subscribe(channelName)
			util.xpcall_loop_check( --- xpcall_loop_check 这是自己写的loop 代码在下面 根据情况自己调整
				function()
					while true do 
						local mes = channelwatching:message() --- 监听到的消息内容 在这里写业务逻辑
					end
				end
			,"crosschannel")	
	end
	channelFunction[channelName](channelName) --- 调起自己的方法 开始监听
end

function CMD.close_cross_channel(channelName) --- 关闭频道
	channels[channelName]:unsubscribe(channelName)
	channels[channelName] = nil
end

require "skynet.datasheet"
skynet.start(function() 
	skynet.dispatch("lua", function(_, _, cmd, ...)
		local c = assert(CMD[cmd], cmd)
		local ret =  c(...)
		skynet.ret(skynet.pack(ret))
	end)
	skynet.register(".CROSSCHANNELMGR")
end)

 这是loop的代码

local skynet = require "skynet"
local sysLog = require("sysLog") --- log

function util.xpcall_loop_check(update, name)
	skynet.fork(function() --- 必须是协程!!! 不然启动while true会阻塞其它服务
		while true do
			local now = os.time()
			local ok, ret = xpcall(update, debug.traceback, now)
			if not ok and ret then 
				sysLog.info("LOOP ERROR", name, ok, ret)
			end
		end
	end)
end

 

你可能感兴趣的:(skynet + redis 发布订阅 多频道开启关闭管理以及监听)