升级CentOS的OpenSSH 搭建SFTP Server

SFTP是 Secure File Transfer Protocol 的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。sftp 与 ftp 有着几乎一样的语法和功能。SFTP 为 SSH的一部分,是一种传输档案至 Blogger 伺服器的安全方式。其实在SSH软件包中,已经包含了一个叫作SFTP(Secure File Transfer Protocol)的安全文件传输子系统,SFTP本身没有单独的守护进程,它必须使用sshd守护进程(端口号默认是22)来完成相应的连接操作,所以从某种意义上来说,SFTP并不像一个服务器程序,而更像是一个客户端程序。SFTP同样是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。

OpenSSH 4.8p1以上的版本才支持SFTP所需的chroot等指令,我的CentOS 5.X服务器的OpenSSH版本过低,需要先对OpenSSH升级。

提示:在升级OpenSSH前,为防止意外出现,我临时开启了telnet,通过telnet连接到服务器后再进行操作(升级完记得关闭telnet)。

service sshd stop #关闭sshd
mv /etc/ssh/sshd_config /etc/ssh/sshd_config_bak #将原有的设置文件改名
wget http://ftp.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-4.9p1.tar.gz
tar zxvf openssh-4.9p1.tar.gz
cd openssh-4.9p1
./configure --prefix=/usr --sysconfdir=/etc/ssh
make
make install

 

如果上面的过程很顺利的话,下面这行命令应该可以正常启动sshd

service sshd start

 

接下来配置sshd_config,设置SFTP的用户和目录

#Subsystem      sftp    /usr/libexec/sftp-server
Subsystem       sftp    internal-sftp

Match User xxxxxx
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
ChrootDirectory /var/htdocs

上面设置中“xxxxxx”替换为你系统中专门用于SFTP的用户名即可,这里我用的是User,也可以用Group来指定一个用户组。

设置好后重启sshd即可。

用SS5在Linux上搭建Socks5 Proxy代理服务器

SOCKS5 是一个代理协议,通过将前端发来的请求转发给真正的目标服务器, 模拟了一个前端的行为。在这里,前端和SOCKS5之间也是通过TCP/IP协议进行通讯,前端将原本要发送给真正服务器的请求发送给SOCKS5服务器,然后SOCKS5服务器将请求转发给真正的服务器。

下面我们将用SS5在Linux上搭建一个Socks5 Proxy Server,具体过程如下:

首先,编译安装SS5需要先安装一些依赖组件

yum -y install gcc gcc-c++ automake make pam-devel openldap-devel cyrus-sasl-devel

接下来,我们从 http://ss5.sourceforge.net/ 下载SS5最新版本的源代码后,开始编译安装:

tar zxvf ./ss5-3.8.9-8.tar.gz
cd ss5-3.8.9
./configure
make
make install

让SS5随系统一起启动

chmod +x /etc/init.d/ss5
chkconfig --add ss5
chkconfig --level 345 ss5 on

开启用户名密码验证机制

vi /etc/opt/ss5/ss5.conf

在ss5.conf中找到auth和permit两行,按照下面的格式进行修改

auth      0.0.0.0/0       -         u
permit u        0.0.0.0/0       -       0.0.0.0/0       -       -       -       -       -

设置用户名和密码

vi /etc/opt/ss5/ss5.passwd

一行一个账号,用户名和密码之间用空格间隔,例如:

user1 123
user2 234

设置端口

vi /etc/sysconfig/ss5

在/etc/sysconfig/ss5这个文件中,添加下面这一行命令,-b后面的参数代表监听的ip地址和端口号

# Add startup option here
SS5_OPTS=" -u root -b 0.0.0.0:8080"

启动

service ss5 start

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

Linux中编译安装Redis和PHP扩展

Redis

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由VMware主持。从2013年5月开始,Redis的开发由Pivotal赞助。

 

下面,我们以Redis 3.0.2为例,对编译安装方法进行说明:

tar zxvf ./redis-3.0.2.tar.gz
cd redis-3.0.2
make
make install //默认情况下会部署到/usr/local/bin目录下

mkdir /etc/redis //用于存放位置文件
mkdir /usr/local/redis //用于存放数据

cd utils
./install_server.sh //运行安装脚本(守护进程、配置文件部署等)

Redis安装好后,接下来我们来为PHP安装Redis扩展:

tar zxvf ./phpredis-2.2.7.tar.gz
cd phpredis-2.2.7
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install

上面的操作完成后,会在/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626目录下生成出一个redis.so文件,下面我们需要把这个so文件加到php.ini中

vi /usr/local/php/etc/php.ini

具体设置如下:

extension_dir="/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"
extension=redis.so

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

通过iptables规则让Linux主机屏蔽Ping

我们以CentOS为例,向iptables中添加如下三条规则:

-A RH-Firewall-1-INPUT -s 192.168.0.100 -p icmp -m icmp --icmp-type 0 -j ACCEPT
-A RH-Firewall-1-INPUT -s 192.168.0.100 -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type 8 -j DROP
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type 0 -j DROP

第1、2行定义了允许192.168.0.100这个ip允许向主机发出Ping请求

第3、4行定义禁止其他所有地址向主机发出Ping请求,接收到的数据包会被丢弃(DROP)

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

在Linux中部署FFmpeg开源视频压缩环境过程简单笔记

下面是在Linux中部署FFmpeg和相关类库全过程的简单记录,如下:

编译安装yasm

tar zxvf ./yasm-1.3.0.tar.gz
cd yasm-1.3.0
./configure
make
make install

编译安装x264

tar xvfj ./x264.tar.bz2
cd x264
./configure --enable-shared
make
make install

编译安装lame

tar zxvf ./lame-3.99.5.tar.gz
cd lame-3.99.5
./configure --enable-shared
make && make install

编译安装libogg

tar zxvf ./libogg-1.3.2.tar.gz
cd libogg-1.3.2
./configure --enable-shared
make && make install

编译安装libvorbis

tar zxvf ./libvorbis-1.3.4.tar.gz
cd libvorbis-1.3.4
./configure
make && make install

编译安装faac

tar zxvf ./faac-1.28.tar.gz
cd faac-1.28
./configure
make && make install

编译安装ffmpeg

tar xvfj ./ffmpeg-2.5.1.tar.bz2
cd ffmpeg-2.5.1
./configure --prefix=/usr/local/ffmpeg2 --enable-libmp3lame --enable-libvorbis --enable-gpl --enable-version3 --enable-nonfree --enable-pthreads --enable-libfaac --enable-libx264 --enable-postproc --enable-ffserver --enable-ffplay
make && make install

# 继续编译 qt-faststart
./configure
make tools/qt-faststart
cp -a tools/qt-faststart /usr/bin/

将libx264写进ldconfig

locate libx264.so.142 #会显示/usr/local/lib/libx264.so.142
ln -s libx264.so.142 libx264.so
vi /etc/ld.so.conf.d/libx264.conf #写入/usr/local/lib
ldconfig

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

采用单例模式编写PHP的PDO类

下面的代码是用此前一个名为MyPDO的类改写的,引入了单例模式来保证在全局调用中不会重复实例化这个类,降低系统资源的浪费。

代码如下:

<?php
/**
 * MyPDO
 * @author Jason.Wei <jasonwei06@hotmail.com>
 * @license http://www.sunbloger.com/
 * @version 5.0 utf8
 */
class MyPDO
{
    protected static $_instance = null;
    protected $dbName = '';
    protected $dsn;
    protected $dbh;
    
    /**
     * 构造
     * 
     * @return MyPDO
     */
    private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        try {
            $this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;
            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
            $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }
    
    /**
     * 防止克隆
     * 
     */
    private function __clone() {}
    
    /**
     * Singleton instance
     * 
     * @return Object
     */
    public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        if (self::$_instance === null) {
            self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
        }
        return self::$_instance;
    }
    
    /**
     * Query 查询
     *
     * @param String $strSql SQL语句
     * @param String $queryMode 查询方式(All or Row)
     * @param Boolean $debug
     * @return Array
     */
    public function query($strSql, $queryMode = 'All', $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $recordset = $this->dbh->query($strSql);
        $this->getPDOError();
        if ($recordset) {
            $recordset->setFetchMode(PDO::FETCH_ASSOC);
            if ($queryMode == 'All') {
                $result = $recordset->fetchAll();
            } elseif ($queryMode == 'Row') {
                $result = $recordset->fetch();
            }
        } else {
            $result = null;
        }
        return $result;
    }
    
    /**
     * Update 更新
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function update($table, $arrayDataValue, $where = '', $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        if ($where) {
            $strSql = '';
            foreach ($arrayDataValue as $key => $value) {
                $strSql .= ", `$key`='$value'";
            }
            $strSql = substr($strSql, 1);
            $strSql = "UPDATE `$table` SET $strSql WHERE $where";
        } else {
            $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        }
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Insert 插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function insert($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Replace 覆盖方式插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function replace($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Delete 删除
     *
     * @param String $table 表名
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function delete($table, $where = '', $debug = false)
    {
        if ($where == '') {
            $this->outputError("'WHERE' is Null");
        } else {
            $strSql = "DELETE FROM `$table` WHERE $where";
            if ($debug === true) $this->debug($strSql);
            $result = $this->dbh->exec($strSql);
            $this->getPDOError();
            return $result;
        }
    }
    
    /**
     * execSql 执行SQL语句
     *
     * @param String $strSql
     * @param Boolean $debug
     * @return Int
     */
    public function execSql($strSql, $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * 获取字段最大值
     * 
     * @param string $table 表名
     * @param string $field_name 字段名
     * @param string $where 条件
     */
    public function getMaxValue($table, $field_name, $where = '', $debug = false)
    {
        $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, 'Row');
        $maxValue = $arrTemp["MAX_VALUE"];
        if ($maxValue == "" || $maxValue == null) {
            $maxValue = 0;
        }
        return $maxValue;
    }
    
    /**
     * 获取指定列的数量
     * 
     * @param string $table
     * @param string $field_name
     * @param string $where
     * @param bool $debug
     * @return int
     */
    public function getCount($table, $field_name, $where = '', $debug = false)
    {
        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, 'Row');
        return $arrTemp['NUM'];
    }
    
    /**
     * 获取表引擎
     * 
     * @param String $dbName 库名
     * @param String $tableName 表名
     * @param Boolean $debug
     * @return String
     */
    public function getTableEngine($dbName, $tableName)
    {
        $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'";
        $arrayTableInfo = $this->query($strSql);
        $this->getPDOError();
        return $arrayTableInfo[0]['Engine'];
    }
    
    /**
     * beginTransaction 事务开始
     */
    private function beginTransaction()
    {
        $this->dbh->beginTransaction();
    }
    
    /**
     * commit 事务提交
     */
    private function commit()
    {
        $this->dbh->commit();
    }
    
    /**
     * rollback 事务回滚
     */
    private function rollback()
    {
        $this->dbh->rollback();
    }
    
    /**
     * transaction 通过事务处理多条SQL语句
     * 调用前需通过getTableEngine判断表引擎是否支持事务
     *
     * @param array $arraySql
     * @return Boolean
     */
    public function execTransaction($arraySql)
    {
        $retval = 1;
        $this->beginTransaction();
        foreach ($arraySql as $strSql) {
            if ($this->execSql($strSql) == 0) $retval = 0;
        }
        if ($retval == 0) {
            $this->rollback();
            return false;
        } else {
            $this->commit();
            return true;
        }
    }

    /**
     * checkFields 检查指定字段是否在指定数据表中存在
     *
     * @param String $table
     * @param array $arrayField
     */
    private function checkFields($table, $arrayFields)
    {
        $fields = $this->getFields($table);
        foreach ($arrayFields as $key => $value) {
            if (!in_array($key, $fields)) {
                $this->outputError("Unknown column `$key` in field list.");
            }
        }
    }
    
    /**
     * getFields 获取指定数据表中的全部字段名
     *
     * @param String $table 表名
     * @return array
     */
    private function getFields($table)
    {
        $fields = array();
        $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
        $this->getPDOError();
        $recordset->setFetchMode(PDO::FETCH_ASSOC);
        $result = $recordset->fetchAll();
        foreach ($result as $rows) {
            $fields[] = $rows['Field'];
        }
        return $fields;
    }
    
    /**
     * getPDOError 捕获PDO错误信息
     */
    private function getPDOError()
    {
        if ($this->dbh->errorCode() != '00000') {
            $arrayError = $this->dbh->errorInfo();
            $this->outputError($arrayError[2]);
        }
    }
    
    /**
     * debug
     * 
     * @param mixed $debuginfo
     */
    private function debug($debuginfo)
    {
        var_dump($debuginfo);
        exit();
    }
    
    /**
     * 输出错误信息
     * 
     * @param String $strErrMsg
     */
    private function outputError($strErrMsg)
    {
        throw new Exception('MySQL Error: '.$strErrMsg);
    }
    
    /**
     * destruct 关闭数据库连接
     */
    public function destruct()
    {
        $this->dbh = null;
    }
}
?>

 

调用方法:

<?php
require 'MyPDO.class.php';
$db = MyPDO::getInstance('localhost', 'root', '123456', 'test', 'utf8');

//do something...

$db->destruct();
?>

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

Linux下管理Memcached的Service脚本

Memcached 的编译安装过程请参考本站的《Linux下部署Memcached和PHP的Memcache扩展方法

如 Memcached 已在 Linux 中安装完毕,且被部署到 /usr/local/memcached 这个路径下,接下来我们来开始为其安装用于启动和停止的服务管理脚本。

首先,通过 vi 在 /etc/rc.d/init.d 路径下新建一个名为 memcached 的脚本文件,命令如下:

vi /etc/rc.d/init.d/memcached

然后,向其中写入 Shell 脚本如下:

#!/bin/sh  
#  
# chkconfig: 2345 90 50
# description: Memcached Service Daemon
#
# processname: Memcached
#
# Source function library.
. /etc/rc.d/init.d/functions
. /etc/sysconfig/network
#[ ${NETWORKING} = "no" ] && exit 0
#[ -r /etc/sysconfig/dund ] || exit 0
#. /etc/sysconfig/dund
#[ -z "$DUNDARGS" ] && exit 0

MEMCACHED="/usr/local/memcached/bin/memcached"

start()
{
    echo -n $"Starting Memcached: "
    daemon $MEMCACHED -u daemon -d -m 32 -l 127.0.0.1 -p 11211 -c 256 -P /tmp/memcached.pid
    echo
}
stop()
{
    echo -n $"Shutting down Memcached: "
    killproc memcached
    echo
}

[ -f $MEMCACHED ] || exit 1
# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 3
        start
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac
exit 0

保存退出 vi 后,执行下面的命令来安装这个脚本

chmod 777 /etc/rc.d/init.d/memcached
chkconfig --add memcached
chkconfig --level 235 memcached on

然后可以通过下面的命令来检查是否安装成功

chkconfig --list | grep memcached
service memcached start
service memcached stop
service memcached restart

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

开源消息队列MemcacheQ在Linux中编译安装教程

队列(Queue)是一种常用的数据结构。在队列这种数据结构中,最先插入的元素将会最先被取出;反之最后插入的元素将会最后被取出,因此队列又称为“先进先出”(FIFO:First In First Out)的线性表。

加入元素的一端叫“队尾”,取出元素的一端叫“队头”。利用消息队列可以很好地异步处理数据的传送和存储,当遇到频繁且密集地向后端数据库中插入数据时,就可采用消息队列来异步处理这些数据写入。

MemcacheQ是一款基于Memcache协议的开源消息队列服务软件,由于其遵循了Memcache协议,因此开发成本很低,不需要学习额外的知识便可轻松掌握。

我在最近的一个项目中也应用了MemcacheQ,下面我将分享一下MemcacheQ在Linux中的编译和安装过程。

首先,MemcacheQ依赖于BerkeleyDB和Libevent,如果服务器中曾经安装过Memcached,那么Libevent应该已经存在了,否则就需要先下载安装Libevent。

下载链接如下:

Libevent:https://github.com/downloads/libevent/libevent/libevent-2.0.21-stable.tar.gz
Berkeley DB:http://download.oracle.com/otn/berkeley-db/db-6.0.30.tar.gz
MemcacheQ:https://github.com/stvchu/memcacheq

安装Libevent

tar zvxf libevent-2.0.21-stable.tar.gz
cd libevent-2.0.21-stable
./configure --prefix=/usr/local/libevent
make && make install
echo "/usr/local/libevent/lib" >> /etc/ld.so.conf
ldconfig

安装BerkeleyDB

BerkeleyDB简介:BerkeleyDB是一个开源的文件数据库,介于关系数据库与内存数据库之间,使用方式与内存数据库类似,它提供的是一系列直接访问数据库的函数,而不是像关系数据库那样需要网络通讯、SQL解析等步骤。

MemcacheQ依赖BerkleyDB用于队列数据的持久化存储,以免在MemcacheQ意外崩溃或中断时,队列数据不会丢失。

tar zxvf db-6.0.30.tar.gz
cd db-6.0.30/build_unix
../dist/configure --prefix=/usr/local/berkeleydb
make && make install
ln -s /usr/local/berkeleydb/lib/libdb-6.0.so /usr/lib/
echo "/usr/local/berkeleydb/lib/" >> /etc/ld.so.conf
ldconfig

安装MemcacheQ

tar zxvf memcacheq-0.2.0.tar.gz
cd memcacheq-0.2.0
./configure --prefix=/usr/local/memcacheq --with-bdb=/usr/local/berkeleydb --with-libevent=/usr/local/libevent --enable-threads
make && make install

启动MemcacheQ

/usr/local/memcacheq/bin/memcacheq -d -uroot -r -l 127.0.0.1 -p11210 -H /usr/local/mcq -N -R -v -L 1024 -B 1024 > /usr/local/mcq/logs/mcq_error.log 2>&1

附:MemcacheQ参数

-p <num>      TCP监听端口(default: 22201)
-U <num>      UDP监听端口(default: 0, off)
-s <file>     unix socket路径(不支持网络)
-a <mask>     unix socket访问掩码(default 0700)
-l <ip_addr>  监听网卡
-d            守护进程
-r            最大化核心文件限制
-u <username> 以用户身份运行(only when run as root)
-c <num>      最大并发连接数(default is 1024)
-v            详细输出 (print errors/warnings while in event loop)
-vv           更详细的输出 (also print client commands/reponses)
-i            打印许可证信息
-P <file>     PID文件
-t <num>      线程数(default 4)

用PHP测试一下

<?php
$mcq = new Memcache;
$mcq->connect('127.0.0.1', 11210) or die ('Connect Error!');
for ($i=1; $i<=5; $i++) {
    memcache_set($mcq, 'k', $i, 0, 0);
}
for ($i=1; $i<=6; $i++) {
    $queue = memcache_get($mcq, 'k');
    if ($queue === false) {
        echo "null\n";
    } else {
        echo $queue."\n";
    }
}

memcache_close($mcq);
?>

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

苹果APNS推送效率研究总结

年底这段时间一直在研究苹果的APNS(英文全称:Apple Push Notification Service)服务,进行了很多尝试,积累了一些经验。写出来总结一下,有不对的地方欢迎指正。

关于推送效率,苹果官方给出的建议是当建立一个Socket通道后,尽可能将需要推送消息和接受的devicetoken连续发送至APNS服务器端。

但是,这里需要注意如果消息队列中存在不正确的devicetoken时,苹果会在接受到这个devicetoken时,强制中断当前的Socket通道,这样会造成后面的消息无法正常发送给APNS服务器。

怎么办?

可能会有人建议每推送一条消息就断开Socket通道重新连接一次,来保证推送成功率。这样做成功率的确可以保证,但效率实在太低。

那怎么办?

很简单,我的做法是在一个消息队列中,每发送一条消息,就去read当前的Socket通道,苹果会在遇到错误的devicetoken后进行标记,我们可以read到这个数据,从而将错误的devicetoken从队列中剔除,并尝试重新建立一个Socket通道,然后从错误的devicetoken后面继续推送。

这样,我们就可以放心大胆的去连续推送一个消息队列,而不用担心由于错误的devicetoken造成推送半途中断。

还有什么办法可以提升推送效率?

最简单的办法就是多线程或多进程处理消息队列,我们团队的做法是多进程,通过HASH将一个消息队列平均分布到多个服务器端的进程上,从而进一步加快推送的速度。

采用多进程还有一个考虑,那就是担心若采用多线程万一遇到某些未知的异常,结果很可能是全军覆没,所有线程一起挂掉。而多进程的状态下,一个进程出现问题,其他的进程还可以继续工作,尽可能将影响降至最低。

速度还能再快吗?

没问题,速度还想进一步提升,就要从网络带宽和服务器方面下功夫了。用n台服务器组成一个消息推送阵列,通过某种策略来分担一定量级的推送任务,每台服务器中再通过前面提到的多进程方式运作,相信效率能够提升的非常明显。

关于feedback

APNS的feedback是一个非常贴心的服务,他会告诉你近期推送的消息,有哪些设备由于卸载了应用而无法在通知中显示消息。

那么,我们通过定期从feedback中获得这些devicetoken后,在数据库中进行标记,在下次的推送中,从消息队列中剔除这些devicetoken,这样减少了无用功,推送一次会完成的更快。

其他建议

本着不重复发明轮子的思想,推荐一下ApnsPHP这个开源项目,这里就不放链接了,github上搜吧:)

阳光部落原创,更多内容请访问http://www.sunbloger.com/

再次深入研究苹果消息推送服务(APNS) 完善PHP版服务器端公共类

前段时间开发的一套APNS推送平台效率很差,通过再次深入研究苹果的消息推送服务,总结了不少经验。同时也参考了网上一些技术blog的博文,重新完善了此前写过的一个PHP类,代码如下:

<?php
/**
 * ApplePush 苹果消息推送公共类
 * @author www.sunbloger.com
 */
class ApplePush
{
    
    const STATUS_CODE_INTERNAL_ERROR = 999;
    const ERROR_RESPONSE_SIZE = 6;
    const ERROR_RESPONSE_COMMAND = 8;
    
    protected $_errorResponseMessages = array(
        0 => 'No errors encountered',
        1 => 'Processing error',
        2 => 'Missing device token',
        3 => 'Missing topic',
        4 => 'Missing payload',
        5 => 'Invalid token size',
        6 => 'Invalid topic size',
        7 => 'Invalid payload size',
        8 => 'Invalid token',
        self::STATUS_CODE_INTERNAL_ERROR => 'Internal error'
    );
    
    /**
     * APNS server url
     * 
     * @var string
     */
    protected $apns_url = 'ssl://gateway.push.apple.com:2195'; //沙盒地址:ssl://gateway.sandbox.push.apple.com:2195
    
    /**
     * 推送数据
     * 
     * @var string
     */
    private $payload_json;
    
    /**
     * 数据流对象
     * 
     * @var mixed
     */
    private $fp;
    
    /**
     * 设置APNS地址
     * 
     * @param string $url
     */
     
    public function setApnsUrl($url)
    {
        if (empty($url)) {
            return false;
        } else {
            $this->apns_url = $url;
        }
        return true;
    }
    
    /**
     * 设置推送的消息
     * 
     * @param string $body
     */
    public function setBody($body)
    {
        if (empty($body)) {
            return false;
        } else {
            $this->payload_json = json_encode($body);
        }
        return true;
    }
    
    /**
     * Open 打开APNS服务器连接
     * 
     * @param string $pem 证书
     * @param string $passphrase 证书密钥
     */
    public function open($pem, $passphrase)
    {
        if (empty($pem)) {
            return false;
        }
        if (empty($passphrase)) {
            return false;
        }
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', $pem);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
        $fp = stream_socket_client($this->apns_url, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        if (!$fp) {
            return false;
        }
        $this->fp = $fp;
        return true;
    }
    
    /**
     * Send 推送
     * 
     * @param string $token
     */
    public function send($token, $id)
    {
        $msg = pack('CNNnH*', 1, $id, 864000, 32, $token) . pack('n', strlen($this->payload_json)) . $this->payload_json;
        // Send it to the server
        $result = fwrite($this->fp, $msg, strlen($msg));
        return $result;
    }
    
    public function readErrMsg()
    {
        $errInfo = @fread($this->fp, self::ERROR_RESPONSE_SIZE);
        if ($errInfo === false || strlen($errInfo) != self::ERROR_RESPONSE_SIZE) {
            return true;
        }
        $errInfo = $this->parseErrMsg($errInfo);
        if (!is_array($errInfo) || empty($errInfo)) {
            return true;
        }
        if (!isset($errInfo['command'], $errInfo['statusCode'], $errInfo['identifier'])) {
            return true;
        }
        if ($errInfo['command'] != self::ERROR_RESPONSE_COMMAND) {
            return true;
        }
        $errInfo['timeline'] = time();
        $errInfo['statusMessage'] = 'None (unknown)';
        $errInfo['errorIdentifier'] = $errInfo['identifier'];
        if (isset($this->_aErrorResponseMessages[$errInfo['statusCode']])) {
            $errInfo['statusMessage'] = $this->_errorResponseMessages[$errInfo['statusCode']];
        }
        return $errInfo;
    }

    protected function parseErrMsg($errorMessage)
    {
        return unpack('Ccommand/CstatusCode/Nidentifier', $errorMessage);
    }
    
    /**
     * Close APNS server 关闭APNS服务器连接
     * 
     */
    public function close()
    {
        // Close the connection to the server
        fclose($this->fp);
        return true;
    }
}
?>

阳光部落原创,更多内容请访问http://www.sunbloger.com/