利用vue+swoole实现推送

推送,有轮询和websocket两种主流方式。轮询是定时执行ajax向后端进行查询。在没有websocket之前我们就采用这种方式。但是Http由于不是全双工的,我们想查询接口就要重复进行http连接,这样非常损耗性能,有了websocket我们只需要连接一次。

首先,在前端我们使用websocket对象进行websocket连接

getNotice(){
     // 打开一个 web socket
     this.ws = new WebSocket("ws://domin");
     this.ws.onopen = ()=>
     {
         //向后端定时发送数据
        setInterval(()=>{
          this.ws.send(this.$store.getters.userInfo.id)
        },1000)
     };
      //接收后端请求回调
     this.ws.onmessage = (evt)=> 
     {
      var noticeCategory=JSON.parse(evt.data); 
      if(noticeCategory!=[]){
        for(var key in noticeCategory){
          switch(key){
            case "followMy":
              var index=1
            break;
            case "reply":
              var index=2
            break;
            case "good":
              var index=3
            break;
          }
          this.$store.commit('setNoticeCategory',{index:index,num:noticeCategory[key]})              
        }
      }
     };

后端使用swoole

<?php 
$server = new swoole_websocket_server("0.0.0.0", 9502);
$server->on('message', function (swoole_websocket_server $server, $frame) {
    $redis=new Redis();
    $redis->pconnect('127.0.0.1',6379);
    $server->push($frame->fd,json_encode($redis->hGetAll($frame->data)));
});
$server->start();
 ?>

假设该php文件的路径为/root/run.php
打开终端

setsid php /root/run.php > /dev/null &

写一个shell监控这个swoole php脚本是否运行

#!/bin/bash
#root\/run 是你的php文件位置
alive=`ps aux|grep root\/run|grep -v grep|wc -l`
#如果没有这个php文件进程了就再次运行这个脚本
if [ $alive -eq 0]
then
php /root/run.php > /dev/null &
fi

假设shell的名字是monitor.sh

chmod 777 monitor.sh

添加计划任务(每分钟检测一次)
crontab -e

* * * * * /root/monitor.sh > /dev/null &

crontab基本格式 :
*  *  *  *  *  command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
crontab文件的一些例子:
30 21 * * * /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每晚的21:30重启apache。
45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每月1、10、22日的4 : 45重启apache。
10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每周六、周日的1 : 10重启apache。
0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart
上面的例子表示在每天18 : 00至23 : 00之间每隔30分钟重启apache。
0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart
上面的例子表示每星期六的11 : 00 pm重启apache。
* */1 * * * /usr/local/etc/rc.d/lighttpd restart
每一小时重启apache
* 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart
晚上11点到早上7点之间,每隔一小时重启apache
0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart
每月的4号与每周一到周三的11点重启apache
0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart
一月一号的4点重启apache
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值