NotifyService.php
class NotifyService extends Model
{
private static $client;
private static $redis;
/**
* 初始化
*/
protected static function initial()
{
$url = 'tcp://' . config('ctrl_service.host') . ':' . config('ctrl_service.port');
self::$client = @stream_socket_client($url, $errno, $errmsg, 1);
if (!self::$client) {
return false;
}
return true;
}
/**
* redis连接
* 接口并发量较高的时候容易造成TIMEWAIT过多
* 尽量避免多次进行连接
*/
private static function redisConnect()
{
// 判断是否使用redis 做缓存 如果有连接过
// if (config('cache.type') == 'redis') {
// // redis 连接 判断是否有已经连接过
// $cache = Cache::init();
// // 获取缓存对象句柄
// $handler = $cache->handler();
// self::$redis = $handler;
// return;
// }
self::$redis = new Redis();
$host = Env::get('redis.host', '127.0.0.1'); // redis 主机ip
$port = Env::get('redis.port', 6379); // redis 端口
$password = Env::get('redis.password', '123456'); // redis 密码
$select = Env::get('cache.select', 0); // 数据库
// 第一个参数为redis服务器的ip,第二个为端口
// self::$redis->connect($host, $port);
self::$redis->pconnect($host, $port);
self::$redis->auth($password); //密码验证
self::$redis->select($select); //选择数据库
}
/**
* redis断开
*/
public static function redisClose()
{
self::$redis->close();
}
/**
* app 通知
*/
public static function appNotify($content, $uid = 0)
{
if (!self::initial()) {
return false;
}
$post_data = [
'cmd' => 1010,
'type' => 'notice',
'uid' => (int) $uid,
'msgid' => 88, // 88是于客户端约定的标识
'content' => json_encode($content),
'loopcount' => 1,
'gid' => 0,
'roomno' => 0,
'interval' => 1,
];
return self::sendMsg($post_data);
}
/**
* 发送消息给控制服转发到游服
*/
public static function sendMsg($data)
{
// 添加一层外壳转发
$msg = [
'content' => $data,
'type' => 'forwarding',
];
$msg = json_encode($msg);
$msg .= "\n";
return fwrite(self::$client, $msg);
}
/**
* 通知中间件配置相关
*/
public static function middleNoticeConfigInit($data, $redis_subscribe = 'middle_config')
{
self::redisConnect();
$data = json_encode($data);
$res = self::$redis->publish($redis_subscribe, $data);
self::redisClose();
}
}
复制代码
// 通知中间件重新获取配置
NotifyService::middleNoticeConfigInit(['type' => 'init_robot_uids']);