查看linux服务器硬盘IO读写负载

用top命令查看

top – 16:15:05 up 6 days,  6:25,  2 users,  load average: 1.45, 1.77, 2.14
Tasks: 147 total,   1 running, 146 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.2% us,  0.2% sy,  0.0% ni, 86.9% id, 12.6% wa,  0.0% hi,  0.0% si
Mem:   4037872k total,  4003648k used,    34224k free,     5512k buffers
Swap:  7164948k total,   629192k used,  6535756k free,  3511184k cached

查看12.6% wa

IO等待所占用的CPU时间的百分比,高过30%时IO压力高

iostat -x 1 10

avg-cpu:  %user   %nice    %sys %iowait   %idle
0.00       0.00     0.25    33.46    66.29

Device:    rrqm/s  wrqm/s   r/s    w/s     rsec/s   wsec/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %util
sda          0.00    0.00      0.00   0.00    0.00    0.00         0.00     0.00     0.00           0.00    0.00    0.00   0.00
sdb          0.00   1122  17.00  9.00  192.00 9216.00    96.00  4608.00   123.79   137.23 1033.43  13.17 100.10
sdc          0.00    0.00     0.00   0.00     0.00     0.00      0.00     0.00     0.00             0.00    0.00      0.00   0.00

查看%util 100.10 %idle 66.29

如果 %util 接近 100%,说明产生的I/O请求太多,I/O系统已经满负荷,该磁盘可能存在瓶颈。

idle小于70% IO压力就较大了,一般读取速度有较多的wait.

vmstat

同时可以结合vmstat 查看查看b参数(等待资源的进程数)

vmstat -1

再通过如下脚本查看高峰的进程io情况

#!/bin/sh
/etc/init.d/syslog stop
echo 1 > /proc/sys/vm/block_dump
sleep 60
dmesg | awk '/(READ|WRITE|dirtied)/ {process[$1]++} END {for (x in process) \
print process[x],x}' |sort -nr |awk '{print $2 " " $1}' | \
head -n 10
echo 0 > /proc/sys/vm/block_dump
/etc/init.d/syslog start

使用rvm安装多个ruby版本

Step 1: Upgrade Packages

# yum update

Step 2: Installing Recommended Packages

# yum install gcc-c++ patch readline readline-devel zlib zlib-devel
# yum install libyaml-devel libffi-devel openssl-devel make
# yum install bzip2 autoconf automake libtool bison iconv-devel

Step 3: Install RVM ( Ruby Version Manager )

# curl -L get.rvm.io | bash -s stable

Step 4: Setup RVM Environment

# source /etc/profile.d/rvm.sh

Step 5: Install Required Ruby Version

# rvm install 1.9.3

Step 6: Setup Default Ruby Version

# rvm use 1.9.3 --default 

Step 7: Check Current Ruby Version

# ruby --version

配置nginx使用letsencrypt免费https证书

https://letsencrypt.org/

生成证书

certbot certonly --webroot \
-w /data/web/c4ys/frontend/web/ -d c4ys.com -d www.c4ys.com \
-w /data/web/c4ys/mobile/web/ -d m.c4ys.com

修改nginx配置

listen       443 ssl;
ssl                  on;
ssl_certificate /etc/letsencrypt/live/www.c4ys.com/fullchain.pem;     
ssl_certificate_key /etc/letsencrypt/live/www.c4ys.com/privkey.pem;
ssl_session_cache    shared:SSL:1m;
ssl_session_timeout  5m;
ssl_ciphers  HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers  on;
error_page 497  https://$host$uri?$args;

自动更新证书

0 3 */10 * * certbot renew –quiet
0 3 */10 * * service nginx restart

inotify-tools + rsync 实现文件自动同步备份

公司图片服务器以前以nfs挂载在各台php-fpm服务器下,最近因为部分fpm服务器迁移到aliyun,远程挂载效率低下,为了本地不修改代码,又可以达到不低,所以想到了inotify + rsync。

inotify-tools介绍:https://github.com/rvoicilas/inotify-tools/wiki

#!/bin/sh

# get the current path
CURPATH=`pwd`

inotifywait -mr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' \
-e close_write /tmp/test | while read date time dir file; do

       FILECHANGE=${dir}${file}
       # convert absolute path to relative
       FILECHANGEREL=`echo "$FILECHANGE" | sed 's_'$CURPATH'/__'`

       rsync --progress --relative -vrae 'ssh -p 22'  $FILECHANGEREL usernam@example.com:/backup/root/dir && \
       echo "At ${time} on ${date}, file $FILECHANGE was backed up via rsync"
done

yii实现redis读写分离

/**
 * FileName:RedisCluster
 * 配置说明
 * 配置为1主多从 或者  1个独立的服务器
 * 写往主的里面写
 * 读是从从的里面读
 * 'class'=>'RedisCache',
 * 'servers'=>array(
 *                array(
 *                   'host'=>'IP1',
 *                   'port'=>'6380',
 *                    'master'=>true //主机
 *                ),
 *                array(
 *                    'host'=>'IP2',
 *                    'port'=>'6381'
 *               )
 *
 * 单独
 * 'class'=>'RedisCache',
 * 'servers'=>array(
 *                array(
 *                   'host'=>'IP1',
 *                   'port'=>'6380',
 *                ),
 
 * @author   zhonghailin
 * @version  v1.0
 * @since    v1.0
 * @Date     2015-3-10 下午4:57:02
 */
class ERedisCache extends CCache{
        
    // 是否使用 M/S 的读写集群方案
    private $_isUseCluster = false;
        
    // Slave 句柄标记
    private $_sn = 0;
        
    // 服务器连接句柄
    private $_linkHandle = array(
        'master'=>null,// 只支持一台 Master
        'slave'=>array(),// 可以有多台 Slave
    );
    //配置文件
    private $_servers=array();
    /**
     * 构造函数
     *
     * @param boolean $isUseCluster 是否采用 M/S 方案
     */
    /*
     * 初始化
     */
    public function init()
    {
        $this->keyPrefix = "";
        parent::init();
        if(is_array($this->_servers)){
            foreach($this->_servers as $servers){
                    if($servers->master){
                        $this->_isUseCluster = true;//如果设置了主服务器那么就是1主多从
                        $this->connect($servers,true);
                    }else{
                        $this->connect($servers);
                    }
            }
        }
    }
     
    /**
     * @return array list of memcache server configurations. Each element is a {@link CMemCacheServerConfiguration}.
     */
    public function getServers()
    {
        return $this->_servers;
    }
     
    /**
     * @param array $config list of memcache server configurations. Each element must be an array
     * with the following keys: host, port, persistent, weight, timeout, retryInterval, status.
     * @see http://www.php.net/manual/en/function.Memcache-addServer.php
     */
    public function setServers($config)
    {
        foreach($config as $c)
            $this->_servers[]=new CRedisServerConfiguration($c);
    }
    /**
     * 连接服务器,注意:这里使用长连接,提高效率,但不会自动关闭
     *
     * @param array $config Redis服务器配置
     * @param boolean $isMaster 当前添加的服务器是否为 Master 服务器
     * @return boolean
     */
    public function connect($config, $isMaster=false){
        // default port
        if(!isset($config->port)){
            $config->port = 6379;
        }
        // 设置 Master 连接
        if($isMaster){
            $this->_linkHandle['master'] = new Redis();
            $ret = $this->_linkHandle['master']->pconnect($config->host,$config->port);
        }else{
            // 多个 Slave 连接
            $this->_linkHandle['slave'][$this->_sn] = new Redis();
            $ret = $this->_linkHandle['slave'][$this->_sn]->pconnect($config->host,$config->port);
            ++$this->_sn;
        }
        return $ret;
    }
        
    /**
     * 关闭连接
     *
     * @param int $flag 关闭选择 0:关闭 Master 1:关闭 Slave 2:关闭所有
     * @return boolean
     */
    public function close($flag=2){
        switch($flag){
            // 关闭 Master
            case 0:
                $this->getRedis()->close();
            break;
            // 关闭 Slave
            case 1:
                for($i=0; $i<$this->_sn; ++$i){
                    $this->_linkHandle['slave'][$i]->close();
                }
            break;
            // 关闭所有
            case 2:
                if(!empty( $this->_linkHandle['master'])){
                    $this->_linkHandle['master']->close();
                }
                for($i=0; $i<$this->_sn; ++$i){
                    $this->_linkHandle['slave'][$i]->close();
                }
            break;
        }
        return true;
    }
        
    /**
     * 得到 Redis 原始对象可以有更多的操作
     *
     * @param boolean $isMaster 返回服务器的类型 true:返回Master false:返回Slave
     * @param boolean $slaveOne 返回的Slave选择 true:负载均衡随机返回一个Slave选择 false:返回所有的Slave选择
     * @return redis object
     */
    public function getRedis($isMaster=true,$slaveOne=true){
        // 只返回 Master
        if($isMaster){
            return $this->_linkHandle['master'];
        }else{
            return $slaveOne ? $this->_getSlaveRedis() : $this->_linkHandle['slave'];
        }
    }
        
    /**
     * 写缓存
     *
     * @param string $key 组存KEY
     * @param string $value 缓存值
     * @param int $expire 过期时间, 0:表示无过期时间
     */
    public function setValue($key, $value, $expire=0){
        // 永不超时
        if($expire == 0){
            if($this->_isUseCluster){
                $ret = $this->getRedis()->set($key, $value);
            }else{
                $ret = $this->getRedis(false)->set($key, $value);
            }
        }else{
            if($this->_isUseCluster){
                 $ret = $this->getRedis()->setex($key, $expire, $value);
            }else{
                 $ret = $this->getRedis(false)->setex($key, $expire, $value);
            }
        }
        return $ret;
    }
        
    /**
     * 读缓存
     *
     * @param string $key 缓存KEY,支持一次取多个 $key = array('key1','key2')
     * @return string || boolean  失败返回 false, 成功返回字符串
     */
    public function getValue($key){
        // 是否一次取多个值
        $func = is_array($key) ? 'mGet' : 'get';
        // 使用了 M/S
        return $this->_getSlaveRedis()->{$func}($key);
    }
        
    /**
     * 条件形式设置缓存,如果 key 不存时就设置,存在时设置失败
     *
     * @param string $key 缓存KEY
     * @param string $value 缓存值
     * @return boolean
     */
    public function setnx($key, $value){
        if($this->_isUseCluster){
            return $this->getRedis()->setnx($key, $value);
        }else{
            return $this->getRedis(false)->setnx($key, $value);
        }
         
    }
        
    /**
     * 删除缓存
     *
     * @param string || array $key 缓存KEY,支持单个健:"key1" 或多个健:array('key1','key2')
     * @return int 删除的健的数量
     */
    public function remove($key){
        if($this->_isUseCluster){
             return $this->getRedis()->delete($key);
        }else{
             return $this->getRedis(false)->delete($key);
        }
    }
     
    /* (non-PHPdoc)
     * @see BaseCache::delete()
     */
    public function deleteValue($key){
        if($this->_isUseCluster){
             return $this->getRedis()->delete($key);
        }else{
             return $this->getRedis(false)->delete($key);
        }
    }
    /**
     * 值加加操作,类似 ++$i ,如果 key 不存在时自动设置为 0 后进行加加操作
     *
     * @param string $key 缓存KEY
     * @param int $default 操作时的默认值
     * @return int 操作后的值
     */
    public function incr($key,$default=1){
        if($default == 1){
            return $this->getRedis()->incr($key);
        }else{
            return $this->getRedis()->incrBy($key, $default);
        }
    }
        
    /**
     * 值减减操作,类似 --$i ,如果 key 不存在时自动设置为 0 后进行减减操作
     *
     * @param string $key 缓存KEY
     * @param int $default 操作时的默认值
     * @return int 操作后的值
     */
    public function decr($key,$default=1){
        if($default == 1){
            return $this->getRedis()->decr($key);
        }else{
            return $this->getRedis()->decrBy($key, $default);
        }
    }
        
    /**
     * 添空当前数据库
     *
     * @return boolean
     */
    public function clear(){
        if(!empty( $this->_linkHandle['master'])){
            $this->_linkHandle['master']->flushDB();
        }
        for($i=0; $i<$this->_sn; ++$i){
            $this->_linkHandle['slave'][$i]->flushDB();
        }
        return true;
    }
        
    /* =================== 以下私有方法 =================== */
        
    /**
     * 随机 HASH 得到 Redis Slave 服务器句柄
     *
     * @return redis object
     */
    private function _getSlaveRedis(){
        // 就一台 Slave 机直接返回
        if($this->_sn <= 1){
            return $this->_linkHandle['slave'][0];
        }
        // 随机 Hash 得到 Slave 的句柄
        $hash = $this->_hashId(mt_rand(), $this->_sn);
        return $this->_linkHandle['slave'][$hash];
    }
        
    /**
     * 根据ID得到 hash 后 0~m-1 之间的值
     *
     * @param string $id
     * @param int $m
     * @return int
     */
    private function _hashId($id,$m=10)
    {
        //把字符串K转换为 0~m-1 之间的一个值作为对应记录的散列地址
        $k = md5($id);
        $l = strlen($k);
        $b = bin2hex($k);
        $h = 0;
        for($i=0;$i<$l;$i++)
        {
            //相加模式HASH
            $h += substr($b,$i*2,2);
        }
        $hash = ($h*1)%$m;
        return $hash;
    }
        
}// End Class
 
 
 
class CRedisServerConfiguration extends CComponent
{
    /**
     * @var string memcache server hostname or IP address
     */
    public $host;
    /**
     * @var integer memcache server port
     */
    public $port=11211;
     
    public $master = false;
    /**
     * Constructor.
     * @param array $config list of memcache server configurations.
     * @throws CException if the configuration is not an array
     */
    public function __construct($config)
    {
        if(is_array($config))
        {
            foreach($config as $key=>$value)
                $this->$key=$value;
            if($this->host===null)
                throw new CException(Yii::t('yii','CMemCache server configuration must have "host" value.'));
        }
        else
            throw new CException(Yii::t('yii','CMemCache server configuration must be an array.'));
    }
}

php取得cpu使用

function getCpuUsage()
{
    $data = getrusage();
    $cpuu = ($data['ru_utime.tv_sec'] + $data['ru_utime.tv_usec'] / 1e6);
    $cpus = ($data['ru_stime.tv_sec'] + $data['ru_stime.tv_usec'] / 1e6);
    $renderedtime = round(microtime(1) - PROFILE_START, 6);
    return [$renderedtime > $cpuu ? $cpuu : 0, $renderedtime > $cpus ? $cpus : 0,];
}

Python set 数据类型

python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.

sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。



下面来点简单的小例子说明把。

>>> x = set('spam')
>>> y = set(['h','a','m'])
>>> x, y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))

再来些小应用。

>>> x & y # 交集
set(['a', 'm'])

>>> x | y # 并集
set(['a', 'p', 's', 'h', 'm'])

>>> x - y # 差集
set(['p', 's'])

记得以前个网友提问怎么去除海量列表里重复元素,用hash来解决也行,只不过感觉在性能上不是很高,用set解决还是很不错的,示例如下:

>>> a = [11,22,33,44,11,22]
>>> b = set(a)
>>> b
set([33, 11, 44, 22])
>>> c = [i for i in b]
>>> c
[33, 11, 44, 22]

很酷把,几行就可以搞定。

1.8 集合 

集合用于包含一组无序的对象。要创建集合,可使用set()函数并像下面这样提供一系列的项:



s = set([3,5,9,10])      #创建一个数值集合

t = set("Hello")         #创建一个唯一字符的集合



与列表和元组不同,集合是无序的,也无法通过数字进行索引。此外,集合中的元素不能重复。例如,如果检查前面代码中t集合的值,结果会是:



>>> t

set(['H', 'e', 'l', 'o'])



注意只出现了一个'l'。

集合支持一系列标准操作,包括并集、交集、差集和对称差集,例如:



a = t | s          # t 和 s的并集

b = t & s          # t 和 s的交集

c = t – s          # 求差集(项在t中,但不在s中)

d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)



基本操作:

t.add('x')            # 添加一项

s.update([10,37,42])  # 在s中添加多项



使用remove()可以删除一项:

t.remove('H')



len(s)
set 的长度

x in s
测试 x 是否是 s 的成员

x not in s
测试 x 是否不是 s 的成员

s.issubset(t)
s <= t
测试是否 s 中的每一个元素都在 t 中

s.issuperset(t)
s >= t
测试是否 t 中的每一个元素都在 s 中

s.union(t)
s | t
返回一个新的 set 包含 s 和 t 中的每一个元素

s.intersection(t)
s & t
返回一个新的 set 包含 s 和 t 中的公共元素

s.difference(t)
s - t
返回一个新的 set 包含 s 中有但是 t 中没有的元素

s.symmetric_difference(t)
s ^ t
返回一个新的 set 包含 s 和 t 中不重复的元素

s.copy()
返回 set “s”的一个浅复制


请注意:union(), intersection(), difference() 和 symmetric_difference() 的非运算符(non-operator,就是形如 s.union()这样的)版本将会接受任何 iterable 作为参数。相反,它们的运算符版本(operator based counterparts)要求参数必须是 sets。这样可以避免潜在的错误,如:为了更可读而使用 set('abc') & 'cbs' 来替代 set('abc').intersection('cbs')。从 2.3.1 版本中做的更改:以前所有参数都必须是 sets。

另外,Set 和 ImmutableSet 两者都支持 set 与 set 之间的比较。两个 sets 在也只有在这种情况下是相等的:每一个 set 中的元素都是另一个中的元素(二者互为subset)。一个 set 比另一个 set 小,只有在第一个 set 是第二个 set 的 subset 时(是一个 subset,但是并不相等)。一个 set 比另一个 set 打,只有在第一个 set 是第二个 set 的 superset 时(是一个 superset,但是并不相等)。

子 set 和相等比较并不产生完整的排序功能。例如:任意两个 sets 都不相等也不互为子 set,因此以下的运算都会返回 False:a<b, a==b, 或者a>b。因此,sets 不提供 __cmp__ 方法。

因为 sets 只定义了部分排序功能(subset 关系),list.sort() 方法的输出对于 sets 的列表没有定义。


运算符
   运算结果

hash(s)
   返回 s 的 hash 值


下面这个表列出了对于 Set 可用二对于 ImmutableSet 不可用的运算:

运算符(voperator)
等价于
运算结果

s.update(t)
s |= t
返回增加了 set “t”中元素后的 set “s”

s.intersection_update(t)
s &= t
返回只保留含有 set “t”中元素的 set “s”

s.difference_update(t)
s -= t
返回删除了 set “t”中含有的元素后的 set “s”

s.symmetric_difference_update(t)
s ^= t
返回含有 set “t”或者 set “s”中有而不是两者都有的元素的 set “s”

s.add(x)

向 set “s”中增加元素 x

s.remove(x)

从 set “s”中删除元素 x, 如果不存在则引发 KeyError

s.discard(x)

如果在 set “s”中存在元素 x, 则删除

s.pop()

删除并且返回 set “s”中的一个不确定的元素, 如果为空则引发 KeyError

s.clear()

删除 set “s”中的所有元素


请注意:非运算符版本的 update(), intersection_update(), difference_update()和symmetric_difference_update()将会接受任意 iterable 作为参数。从 2.3.1 版本做的更改:以前所有参数都必须是 sets。

还请注意:这个模块还包含一个 union_update() 方法,它是 update() 方法的一个别名。包含这个方法是为了向后兼容。程序员们应该多使用 update() 方法,因为这个方法也被内置的 set() 和 frozenset() 类型支持。

php mysql实现非连续不重复ID

非连续ID有很多用处.最大的一个用处就是作为订单id,用户id之类的不想让别人遍历(直接通过请求里面传id值来爬你的数据),以及不想让别人看出来你有多少数据量(如果是连续id,应用有多少订单,一目了然)的id.

mysql的实现方法

添加一个触发器,每次插入的时候通过取当前最大的id然后加一个随机数得到新的id.

   CREATE TRIGGER `rand_increase` BEFORE INSERT ON `users` FOR EACH ROW SET NEW.id=(SELECT max(id) FROM users)+FLOOR(RAND()*500)

php的实现方法

生成一个ID,到数据库里面查看ID是否存在,如果存在,再生成一个.

class model
{
    public function generateRandomId($length=15) {
        $random = "";
        for ($i = 0; $i < $length; $i++) {
            $random .= mt_rand(0, 9);
        }
        return $random;
    }
    public function beforeInsert() {
        do{
            $inserId=$this->generateRandomId(10);
        }while(!$this->selectById($inserId));
        $this->insertId=$inserId;
    }
}

理论上,在超高并发条件下,这两种方法都不是完美的解决办法,但是实际上只要你的id不是太短(比如15位以上?),不完美发生的概率非常非常非常非常非常非常非常非常小.

来源:php mysql实现非连续不重复ID