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/

在Linux中用Shell脚本完成SVN版本库的建立

每次建立一个新的SVN版本库总感觉很繁琐,所以写了段脚本来把这个过程自动化,详细代码如下:

#!/bin/bash
# by www.sunbloger.com

echo -n "Enter SVN name :"
read svn_name
/usr/bin/svnadmin create /svnroot/$svn_name
if [ $? -eq 0 ]; then
    
    # svnserve.conf
    sed -i 's/# anon-access = read/anon-access = none/g' /svnroot/$svn_name/conf/svnserve.conf
    sed -i 's/# auth-access = write/auth-access = write/g' /svnroot/$svn_name/conf/svnserve.conf
    sed -i 's/# password-db = passwd/password-db = \/svnroot\/conf\/passwd/g' /svnroot/$svn_name/conf/svnserve.conf
    sed -i 's/# authz-db = authz/authz-db = authz/g' /svnroot/$svn_name/conf/svnserve.conf
    
    # authz
    cat > /svnroot/$svn_name/conf/authz<<EOF
[groups]
developer = jason
[/]
@developer = rw
EOF

fi

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

MySQL获取自增主键ID的四种方法

1. SELECT MAX(id) FROM tablename

2. LAST_INSERT_ID() 函数

LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。

在多用户交替插入数据的情况下MAX(id)显然不能用。这时就该使用LAST_INSERT_ID了,因为LAST_INSERT_ID是基于Connection的,只要每个线程都使用独立的 Connection对象,LAST_INSERT_ID函数将返回该Connection对AUTO_INCREMENT列最新的insert or update 操作生成的第一个record的ID。这个值不能被其它客户端(Connection)影响,保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁。使用单INSERT语句插入多条记录, LAST_INSERT_ID返回一个列表。

3. SELECT @@IDENTITY;

@@identity 是表示的是最近一次向具有identity属性(即自增列)的表插入数据时对应的自增列的值,是系统定义的全局变量。一般系统定义的全局变量都是以@@开头,用户自定义变量以@开头。

比如有个表A,它的自增列是id,当向A表插入一行数据后,如果插入数据后自增列的值自动增加至101,则通过select @@identity得到的值就是101。使用@@identity的前提是在进行insert操作后,执行select @@identity的时候连接没有关闭,否则得到的将是NULL值。

4. SHOW TABLE STATUS;

得出的结果里边对应表名记录中有个Auto_increment字段,里边有下一个自增ID的数值就是当前该表的最大自增ID。

上述内容来自互联网