Skip to content

Instantly share code, notes, and snippets.

@wrj913
Last active April 3, 2020 15:28
Show Gist options
  • Save wrj913/c6047c9a4b2689b40ceb38f63eefac17 to your computer and use it in GitHub Desktop.
Save wrj913/c6047c9a4b2689b40ceb38f63eefac17 to your computer and use it in GitHub Desktop.
开发环境部署

CentOS 使用yum安装MYSQL

1 查看Linux发行版本

cat /etc/redhat-release
显示:
CentOS Linux release 7.2.1511 (Core)

2 下载MySQL官方的Yum Repository

根据Linux发行版本(CentOS、Fedora都属于红帽系),从mysql官方(http://dev.mysql.com/downloads/repo/yum/)获取Yum Repository。

wget -i http://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm

3 安装MySQL的Yum Repository

安装完MySQL的Yum Repository,每次执行yum update都会检查MySQL是否更新。

yum -y install mysql57-community-release-el7-7.noarch.rpm

4 安装MySQL数据库的服务器版本

yum -y install mysql-community-server

安装完成:

Running transaction
  Installing : mysql-community-common-5.7.17-1.el7.x86_64                                                                                                                                                     1/7 
  Installing : mysql-community-libs-5.7.17-1.el7.x86_64                                                                                                                                                       2/7 
  Installing : mysql-community-client-5.7.17-1.el7.x86_64                                                                                                                                                     3/7 
  Installing : net-tools-2.0-0.17.20131004git.el7.x86_64                                                                                                                                                      4/7 
  Installing : mysql-community-server-5.7.17-1.el7.x86_64                                                                                                                                                     5/7 
  Installing : mysql-community-libs-compat-5.7.17-1.el7.x86_64                                                                                                                                                6/7 
  Erasing    : 1:mariadb-libs-5.5.44-2.el7.centos.x86_64                                                                                                                                                      7/7 
  Verifying  : mysql-community-common-5.7.17-1.el7.x86_64                                                                                                                                                     1/7 
  Verifying  : mysql-community-server-5.7.17-1.el7.x86_64                                                                                                                                                     2/7 
  Verifying  : net-tools-2.0-0.17.20131004git.el7.x86_64                                                                                                                                                      3/7 
  Verifying  : mysql-community-libs-5.7.17-1.el7.x86_64                                                                                                                                                       4/7 
  Verifying  : mysql-community-libs-compat-5.7.17-1.el7.x86_64                                                                                                                                                5/7 
  Verifying  : mysql-community-client-5.7.17-1.el7.x86_64                                                                                                                                                     6/7 
  Verifying  : 1:mariadb-libs-5.5.44-2.el7.centos.x86_64                                                                                                                                                      7/7 

Installed:
  mysql-community-libs.x86_64 0:5.7.17-1.el7                        mysql-community-libs-compat.x86_64 0:5.7.17-1.el7                        mysql-community-server.x86_64 0:5.7.17-1.el7                       

Dependency Installed:
  mysql-community-client.x86_64 0:5.7.17-1.el7                          mysql-community-common.x86_64 0:5.7.17-1.el7                          net-tools.x86_64 0:2.0-0.17.20131004git.el7                         

Replaced:
  mariadb-libs.x86_64 1:5.5.44-2.el7.centos                                                                                                                                                                       

Complete!

5 启动数据库:

systemctl start  mysqld.service

然后使用命令sudo systemctl status mysqld.service查看MySQL数据库启动后的服务状态:

● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-02-10 01:46:00 GMT; 6min ago
     Docs: man:mysqld(8)
           http://dev.mysql.com/doc/refman/en/using-systemd.html
  Process: 20655 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
  Process: 20581 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
 Main PID: 20659 (mysqld)
   CGroup: /system.slice/mysqld.service
           └─20659 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid

Feb 10 01:45:35 localhost.localdomain systemd[1]: Starting MySQL Server...
Feb 10 01:46:00 localhost.localdomain systemd[1]: Started MySQL Server.

6 获取初始密码

使用YUM安装并启动MySQL服务后,MySQL进程会自动在进程日志中打印root用户的初始密码:

#######从mysql进程日志中获取root用户的初始密码:ofX20zWOu6:o
 grep "password" /var/log/mysqld.log
2017-02-10T01:45:38.393132Z 1 [Note] A temporary password is generated for root@localhost: ofX20zWOu6:o
2017-02-10T01:53:54.809923Z 4 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2017-02-10T01:53:59.195263Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2017-02-10T01:58:50.900865Z 7 [Note] Access denied for user 'root'@'localhost' (using password: YES)

7 修改root用户密码

使用小节6中获取的root用户的初始密码,然后进行修改:

mysql -uroot -p
  • -h127.0.0.1 其中“-p”是参数,“rootpassword”,默认本地参数可忽略
  • -P3306 其中“-P”是参数(注意大写),“3306”,默认本地参数可忽略
  • -uroot 其中“-u”是参数,“root” 是用户名。
  • -prootpassword 其中“-p”是参数,“rootpassword” 是用户名。
  • Commands end with ; or \g. 命令的结束符,用“;”或者“\g”符号结束,但是冒号结束退出是不行的。
  • Your MySQL connection id is 99 其中 id 表示客户端的连接 ID,该数据记录了 MySQL 服务到目前为止的连接次数,每次新连接都会自动加 1。由于数据库服务是我安装了好久的,所以当前 ID 值为 99。
  • Server version: 5.7.14 MySQL MySQL的版本。
  • Community Server (GPL) 表示 MySQL 软件是社区版。
  • Type 'help;' or '\h' for help. 表示输入 “help;” 或者 “\h” 命令可以查看帮助信息。
  • Type '\c' to clear the current input statement. 表示输入“\c” 命令可以清除前面的命令。

你只需要在mysql>命令中输入 SQL 语句,同时并以分号“;”结束。最后摁Enter键即可操作 MySQL软件。

当然,具体的版本和连接信息可能不同,但都可以使用这个实用程序。请注意:

  • 命令输入在mysql> 之后;
  • q\quitexit三种命令可以退出命令行实用程序;
  • 帮助命令,输入help\h获得帮助,可以获得其它特定的命令的帮助(如,输入help select获得使用SELECT语句的帮助);

修改密码:

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('root');
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

报错:在Google上搜索下http://www.cnblogs.com/ivictor/p/5142809.html

发现与 validate_password插件有关,MySQL5.7是默认安装的。

  • 当你报下面错误,提示您的密码不满足当前的策略要求。错误如下:

    ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
    # 或者
    mysqladmin: unable to change password; error: 'Your password does not satisfy the current policy requirements'
    

    解决方法:可以按照现有策略设置密码,也可以更改密码策略。

    # 更改密码策略为LOW
    MySQL> set global validate_password_policy=0;
    # 更改密码长度 密码最小长度为4
    MySQL> set global validate_password_length=4;  
    

    进入 MySQL 查看你的密码验证策略

    mysql> SHOW VARIABLES LIKE 'validate_password%';
    +--------------------------------------+-------+
    | Variable_name                        | Value |
    +--------------------------------------+-------+
    | validate_password_check_user_name    | OFF   | 
    | validate_password_dictionary_file    |       | 
    | validate_password_length             | 4     | 
    | validate_password_mixed_case_count   | 1     | 
    | validate_password_number_count       | 1     | 
    | validate_password_policy             | LOW   | 
    | validate_password_special_char_count | 1     | 
    +--------------------------------------+-------+
    7 rows in set (0.00 sec)
    
    • validate_password_check_user_name 不得使用当前会话用户名作为密码的一部分
    • validate_password_dictionary_file 验证密码强度的字典文件路径
    • validate_password_length 密码最小长度
    • validate_password_mixed_case_count 密码至少要包含的小写字母个数和大写字母个数
    • validate_password_number_count 密码至少要包含的数字个数
    • validate_password_policy 密码强度检查等级,0/LOW、1/MEDIUM、2/STRONG
      • 0/LOW:只检查长度。
      • 1/MEDIUM:检查长度、数字、大小写、特殊字符。
      • 2/STRONG:检查长度、数字、大小写、特殊字符字典文件。
    • validate_password_special_char_count 密码至少要包含的特殊字符数

8 安装完毕

至此,使用在CentOS7中使用YUM方法安装MySQL5.7.10数据库完毕。如下所示,可以使用新的root密码登陆MySQL了。

mysql -uroot -ppassword

9 创建用户与授权

创建用户:

    命令:CREATE USER username IDENTIFIED BY 'password';

说明:
  • username:你将创建的用户名
  • host:指定该用户在哪个主机上可以登陆,如果是本地用户可用localhost,如果想让该用户可以从任意远程主机登陆,可以使用通配符%
  • password:该用户的登陆密码,密码可以为空,如果为空则该用户可以不需要密码登陆服务器
例子:

    示例:

CREATE USER 'dog'@'localhost' IDENTIFIED BY '123456';
CREATE USER 'pig'@'192.168.1.101_' IDENDIFIED BY '123456';
CREATE USER 'pig'@'%' IDENTIFIED BY '123456';
CREATE USER 'pig'@'%' IDENTIFIED BY '';
CREATE USER 'pig'@'%';

2.授权

命令:
GRANT privileges ON databasename.tablename TO 'username'@'host'
说明:
  • privileges:用户的操作权限,如SELECTINSERTUPDATE等,如果要授予所的权限则使用ALL
  • databasename:数据库名
  • tablename:表名,如果要授予该用户对所有数据库和表的相应操作权限则可用*表示,如*.*
例子:
GRANT SELECT, INSERT ON test.user TO 'pig'@'%';
GRANT ALL ON *.* TO 'pig'@'%';
注意:

用以上命令授权的用户不能给其它用户授权,如果想让该用户可以授权,用以下命令:

GRANT privileges ON databasename.tablename TO 'username'@'host' WITH GRANT OPTION;

nginx 编译安装

##一、安装nginx时必须先安装相应的编译工具 sudo yum -y install gcc gcc-c++ autoconf automake libtool make zlib zlib-devel openssl openssl-devel pcre-devel zlib:nginx提供gzip模块,需要zlib库支持 openssl:nginx提供ssl功能 pcre:支持地址重写rewrite功能

###建立nginx 组 groupadd -r nginx useradd -s /sbin/nologin -g nginx -r nginx id nginx

##二、 install nginx ###下载nginx http://nginx.org/en/download.html

cd /usr/local/src/
wget http://nginx.org/download/nginx-1.11.0.tar.gz

解压

tar -zxvf nginx-1.2.8.tar.gz
cd nginx-1.11.0

编译

./configure \
--prefix=/usr \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--pid-path=/var/run/nginx/nginx.pid \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_gzip_static_module \
--http-log-path=/var/log/nginx/access.log \
--http-client-body-temp-path=/var/tmp/nginx/client \
--http-proxy-temp-path=/var/tmp/nginx/proxy \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi \
--with-http_stub_status_module

configure 成功后会如下显示:

Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + md5: using OpenSSL library
  + sha1: using OpenSSL library
  + using system zlib library
  + jemalloc library is disabled

  nginx path prefix: "/usr"
  nginx binary file: "/usr/sbin/nginx"
  nginx configuration prefix: "/etc/nginx"
  nginx configuration file: "/etc/nginx/nginx.conf"
  nginx pid file: "/var/run/nginx/nginx.pid"
  nginx error log file: "/var/log/nginx/error.log"
  nginx http access log file: "/var/log/nginx/access.log"
  nginx http client request body temporary files: "/var/tmp/nginx/client"
  nginx dso module path: "/usr/modules/"
  nginx http proxy temporary files: "/var/tmp/nginx/proxy"
  nginx http fastcgi temporary files: "/var/tmp/nginx/fcgi"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

编译:

make && make install

##三、安装nginx 自启动服务

nginx service 脚本链接,复制文件到etc/init.d

cp nginx /etc/init.d/nginx

使用chkconfig --add添加到启动的服务

chkconfig --add myservice

查看是否添加成功 ​ chkconfig --list nginx

php5.5 编译安装

##安装依赖 yum install -y gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libpng libpng-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses curl openssl-devel gdbm-devel db4-devel libXpm-devel libX11-devel gd-devel gmp-devel readline-devel libxslt-devel expat-devel xmlrpc-c xmlrpc-c-devel php-mcrypt libmcrypt libmcrypt-devel

##下载

http://php.net/downloads.php 下载

解压:

tar -zxvf php-5.5.xx.tar.gz  

##安装 1.config php扩展的目录,请看configure --prefix参数,如上配置/usr/local/php-56/lib/php/extensions/,扩展的配置文件请看configure --with-config-file-path参数,如上/etc/php/56,在/etc/php/56目录下建立conf.d目录,扩展配置的配置文件放到conf.d目录下,如mcrypt.so扩展配置文件mcrypt.ini

sudo ./configure  --enable-fpm  --with-fpm-user=www  --with-fpm-group=www  --prefix=/usr/local/php-55  --with-config-file-path=/etc/php/55  --sysconfdir=/etc/php/55  --with-config-file-scan-dir=/etc/php/55/conf.d  --enable-mbstring  --enable-pcntl  --with-mysql=mysqlnd  --with-zlib  --with-png-dir  --with-jpeg-dir  --with-freetype-dir  --with-gd  --enable-gd-native-ttf  --with-curl=shared  --with-mysqli=mysqlnd  --enable-soap=shared  --enable-sockets=shared  --enable-mysqlnd  --with-pdo-mysql=mysqlnd  --with-gettext=shared  --with-mcrypt=shared  --with-openssl=share --with-openssl --enable-json


下面是一份config参数的注释 ​
–with-mysql=/usr/local/mysql mysql安装目录,对mysql的支持
–with-mysqli=/usr/local/mysql/bin/mysql_config mysqli文件目录,优化支持
–enable-safe-mode 打开安全模式
–enable-ftp 打开ftp的支持
–enable-zip 打开对zip的支持
–with-bz2 打开对bz2文件的支持
–with-jpeg-dir 打开对jpeg图片的支持
–with-png-dir 打开对png图片的支持
–with-freetype-dir 打开对freetype字体库的支持
–without-iconv 关闭iconv函数,种字符集间的转换
–with-libxml-dir 打开libxml2库的支持
–with-xmlrpc 打开xml-rpc的c语言
–with-zlib-dir 打开zlib库的支持
–with-gd 打开gd库的支持
–enable-gd-native-ttf 支持TrueType字符串函数库
–with-curl 打开curl浏览工具的支持
–with-curlwrappers 运用curl工具打开url流
–with-ttf 打开freetype1.*的支持,可以不加了
–with-xsl 打开XSLT 文件支持,扩展了libxml2库 ,需要libxslt软件
–with-gettext 打开gnu 的gettext 支持,编码库用到
–with-pear 打开pear命令的支持,php扩展用的
–enable-calendar 打开日历扩展功能
–enable-mbstring 多字节,字符串的支持
–enable-bcmath 打开图片大小调整,用到zabbix监控的时候用到了这个模块
–enable-sockets 打开 sockets 支持
–enable-exif 图片的元数据支持
–enable-magic-quotes 魔术引用的支持
–disable-rpath 关闭额外的运行库文件
–disable-debug 关闭调试模式
–with-mime-magic=/usr/share/file/magic.mime 魔术头文件位置
cgi方式安装才用的参数
–enable-fpm 打上php-fpm 补丁后才有这个参数,cgi方式安装的启动程序
–enable-fastcgi 支持fastcgi方式启动php
–enable-force-cgi-redirect 同上 ,帮助里没有解释
–with-ncurses 支持ncurses 屏幕绘制以及基于文本终端的图形互动功能的动态库
–enable-pcntl freeTDS需要用到的,可能是链接mssql 才用到
mhash和mcrypt算法的扩展
–with-mcrypt 算法
–with-mhash 算法
–with-gmp
–enable-inline-optimization
–with-openssl openssl的支持,加密传输时用到的
–enable-dbase
–with-pcre-dir=/usr/local/bin/pcre-config perl的正则库案安装位置
–disable-dmalloc
–with-gdbm dba的gdbm支持
–enable-sigchild
–enable-sysvsem
–enable-sysvshm
–enable-zend-multibyte 支持zend的多字节
–enable-mbregex
–enable-wddx
–enable-shmop
–enable-soap
PHP配置选项完整列表
数据库选项
–with-dbplus
包括 dbplus 的支持。
–with-adabas[=DIR]
包括 Adabas D 的支持。DIR 是 Adabas 的基本安装目录,默认为 /usr/local。
–with-sapdb[=DIR]
包括 SAP DB 的支持。DIR 是 SAP DB 的基本安装目录,默认为 /usr/local。
–with-solid[=DIR]
包括 Solid 的支持。DIR 是 Solid 的基本安装目录,默认为 /usr/local/solid。
–with-ibm-db2[=DIR]
包括 IBM DB2 的支持。DIR 是 DB2 的基本安装目录,默认为 /home/db2inst1/sqllib。
–with-empress[=DIR]
包括 Empress 的支持。DIR 是 Empress 的基本安装目录,默认为 $EMPRESSPATH。自 PHP4 起,本选项仅支持 Empress 8.60 及以上版本。
–with-empress-bcs[=DIR]
包括 Empress Local Access 的支持。DIR 是 Empress 的基本安装目录,默认为 $EMPRESSPATH。自 PHP4 起,本选项仅支持 Empress 8.60 及以上版本。
–with-birdstep[=DIR]
包括 Birdstep 的支持。DIR 是 Birdstep 的基本安装目录,默认为 /usr/local/birdstep。
–with-custom-odbc[=DIR]
包 括用户自定义 ODBC 的支持。DIR 是 ODBC 的基本安装目录,默认为 /usr/local。要确认定义了 CUSTOM_ODBC_LIBS 并且在 include 目录中有某个 odbc.h。例如,对于 QNX 下的 Sybase SQL Anywhere 5.5.00,在运行 configure 脚本之前应该先定义以下环境变量: CPPFLAGS=”-DODBC_QNX -DSQLANY_BUG” LDFLAGS=-lunix CUSTOM_ODBC_LIBS=”-ldblib -lodbc”.
–with-iodbc[=DIR]
包括 iODBC 的支持。DIR 是 iODBC 的基本安装目录,默认为 /usr/local。
–with-esoob[=DIR]
包括 Easysoft OOB 的支持。DIR 是 OOB 的基本安装目录,默认为 /usr/local/easysoft/oob/client。
–with-unixODBC[=DIR]
包括 unixODBC 的支持。DIR 是 unixODBC 的基本安装目录,默认为 /usr/local。
–with-openlink[=DIR]
包括 OpenLink ODBC 的支持。DIR 是 OpenLink 的基本安装目录,默认为 /usr/local。这和 iODBC 一样。
–with-dbmaker[=DIR]
包括 DBMaker 的支持。DIR 是 DBMaker 的基本安装目录,默认为最新版 DBMaker 安装的目录(例如 /home/dbmaker/3.6)。
–disable-unified-odbc
取消对 unified ODBC 的支持。仅适用于激活了 iODBC,Adabas,Solid,Velocis 或用户自定义 ODBC 界面。仅能用于 PHP 3!
图像选项
–without-gd
禁用 GD 支持。仅用于 PHP 3!
–with-imagick
Imagick 扩展被移到 PEAR 中的 PECL 中去了,可以在这里找到。PHP 4 中的安装指示可以在 PEAR 站点中找到。
只用 –with-imagick 仅在 PHP 3 中支持,除非依照 PEAR 站点的指示去做。
–with-ming[=DIR]
包括 ming 支持。
杂类选项
–enable-force-cgi-redirect
激活服务器内部重定向的安全检查。如果是在 Apache 中以 CGI 方式使用 PHP 则应该使用此选项。
–enable-discard-path
使用此选项可以使 PHP 的 CGI 可执行程序安全地放置在 web 目录树以外的地方,并且别人也不能绕过 .htaccess 的安全设置。
–with-fastcgi
将 PHP 编译成 FastCGI 应用程序。
–enable-debug
编译时加入调试符号。
–with-layout=TYPE
设置安装后的文件布局。TYPE 可以是 PHP(默认值)或者 GNU。
–with-pear=DIR
将 PEAR 安装在 DIR 目录中(默认为 PREFIX/lib/php)。
–without-pear
不安装 PEAR。
–enable-sigchild
激活 PHP 自己的 SIGCHLD 句柄。
–disable-rpath
禁止传递附加的运行时库搜索路径。
–enable-libgcc
激活显式 libgcc 连接。
–enable-php-streams
包含试验的 PHP 流。除非是测试源代码,否则不要使用!
–with-zlib-dir=

;
定义 zlib 的安装路径。
–with-aspell[=DIR]
包含 ASPELL 支持。
–with-ccvs[=DIR]
包含 CCVS 支持。
–with-cybercash[=DIR]
包含 CyberCash 支持。DIR 是 CyberCash MCK 的安装目录。
–with-icap[=DIR]
包含 ICAP 支持。
–with-ircg-config
ircg-config 脚本的路径。
–with-ircg
包含 ircg 支持。
–enable-mailparse
包含 mailparse 支持。
–with-muscat[=DIR]
包含 muscat 支持。
–with-satellite[=DIR]
激活通过 Satellite(试验性质)的 CORBA 支持。DIR 是 ORBit 的主目录。
–enable-trans-sid
激活透明的 session id 传播。
–with-regex[=TYPE]
使用系统 regex 库(不赞成)。
–with-vpopmail[=DIR]
包含 vpopmail 支持。
–with-tsrm-pthreads
使用 POSIX 线程(默认值)。
–enable-shared[=PKGS]
编译共享库 [default=yes]。
–enable-static[=PKGS]
编译静态库 [default=yes]。
–enable-fast-install[=PKGS]
为快速安装而优化 [default=yes]。
–with-gnu-ld
假定 C 编译器使用 GNU ld [default=no]。
–disable-libtool-lock
避免锁死(可能会破坏并行编译)。
–with-pic
尝试只使用 PIC/non-PIC 对象 [default=use both]。
–enable-memory-limit
编译时加入内存限制支持。
–disable-url-fopen-wrapper
禁止通过 URL 的 fopen wrapper,不能通过 HTTP 或 FTP 访问文件。
–enable-versioning
仅输出所需要的符号。更多信息见 INSTALL 文件。
–with-imsp[=DIR]
包含 IMSp 支持(DIR 是 IMSP 的 include 目录和 libimsp.a 目录)。仅用于 PHP 3!
–with-mck[=DIR]
包含 Cybercash MCK 支持。DIR 是 cybercash mck 编译目录,默认为 /usr/src/mck-3.2.0.3-linux。帮助见 extra/cyberlib。仅用于 PHP 3!
–with-mod-dav=DIR
包含通过 Apache 的 mod_dav 的 DAV 支持。DIR 是 mod_dav 的安装目录(仅用于 Apache 模块版本!)仅用于 PHP 3!
–enable-debugger
编译入远程调试函数。仅用于 PHP 3!
–enable-versioning
利用 Solaris 2.x 和 Linux 提供的版本控制与作用范围的优势。仅用于 PHP 3!
PHP 选项
–enable-maintainer-mode
激活将编译规则和未使用的(以及一些混淆的)依赖文件放入临时安装中。
–with-config-file-path=PATH
设定 php.ini 所在的路径,默认为 PREFIX/lib。
–enable-safe-mode
默认激活安全模式。
–with-exec-dir[=DIR]
安全模式下只允许此目录下执行程序。默认为 /usr/local/php/bin。
–enable-magic-quotes
默认激活 magic quotes。
–disable-short-tags
默认禁止简写的 PHP 开始标记 <?。
服务器选项
–with-aolserver=DIR
指定已安装的 AOLserver 的路径。
–with-apxs[=FILE]
编译共享 Apache 模块。FILE 是可选的 Apache 的 apxs 工具的路径,默认为 apxs。确保指定的 apxs 版本是安装后的文件而不是 Apache 源程序中包中的。
–with-apache[=DIR]
编译 Apache 模块。DIR 是 Apache 源程序的最高一级目录。默认为 /usr/local/apache。
–with-mod_charset
激活 mod_charset 中的传递表(Apache 中)。
–with-apxs2[=FILE]
编译共享的 Apache 2.0 模块。FILE 是可选的 Apache 的 apxs 工具的路径,默认为 apxs。
–with-fhttpd[=DIR]
编译 fhttpd 模块。DIR 是 fhttpd 的源代码路径,默认为 /usr/local/src/fhttpd。
–with-isapi=DIR
将 PHP 编译为 ISAPI 模块用于 Zeus。
–with-nsapi=DIR
指定已安装的 Netscape 服务器路径。
–with-phttpd=DIR
暂无信息。
–with-pi3web=DIR
将 PHP 编译为用于 Pi3Web 的模块。
–with-roxen=DIR
将 PHP 编译为一个 Pike 模块。DIR 是 Roxen 的根目录,通常为 /usr/local/roxen/server。
–enable-roxen-zts
编译 Roxen 模块,使用 Zend Thread Safety。
–with-servlet[=DIR]
包含 servlet 支持。DIR 是 JSDK 的基本安装目录。本 SAPI 需要 java 扩展必须被编译为共享的 dl。
–with-thttpd=SRCDIR
将 PHP 编译为 thttpd 模块。
–with-tux=MODULEDIR

sudo make && sudo make install

3.将php55软链到/usr/sbin下

sudo ln -s /usr/local/php-55/bin/php /usr/sbin/php55

4.配置php-fpm

cp /etc/php/55/php-fpm.conf.default /etc/php/55/php-fpm.conf
vi /etc/php/55/php-fpm.conf

对/etc/php/55/php-fpm.conf做如下调整

25行
;pid = run/php-fpm.pid => pid = run/php-fpm.pid
32行
;error_log = log/php-fpm.log => error_log = log/php-fpm.log
164行
listen = 127.0.0.1:9000 => listen = /dev/shm/php55-socket
176行 177行 178行 
;listen.owner = www => listen.owner = www
;listen.group = www => listen.group = www
;listen.mode = 0660 => listen.mode = 0660

##添加启动的sevice 添加php55-fpm service,在/etc/init.d目录下新建php55-fpm文件,脚本链接

##配置环境变量 在/etc/profile.d 添加path.sh ​ export PATH=/usr/local/php-55/bin:$PATH source profile

输入php -v 测试

#!/bin/sh
# nginx - this script starts and stops the nginx daemin
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
#
### BEGIN INIT INFO
# Provides: nginx
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 2 3 5
# Default-Stop: 0 1 6
# Description: Start or stop the nginx server
### END INIT INFO
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
lockfile=/var/lock/nginx.lock
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
pgrep $prog > /dev/null
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
$nginx -s reload > /dev/null
#killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
user www;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 102400;
error_log /var/log/nginx/error.log error;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
use epoll;
accept_mutex off;
worker_connections 102400;
}
http {
include mime.types;
default_type application/octet-stream;
set_real_ip_from 10.1.0.0/16;
real_ip_header X-Real-IP;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format beibei.com '$remote_addr - $remote_user [$time_local] "$request_method $http_host$request_uri $server_protocol" '
'$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
log_format log_post '$remote_addr - $remote_user [$time_local] "$request_method $http_host$request_uri $request_body $server_protocol" '
'$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
#access_log /dev/null;
#sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 15;
proxy_connect_timeout 15;
proxy_read_timeout 300;
proxy_send_timeout 300;
fastcgi_connect_timeout 15;
fastcgi_send_timeout 150;
fastcgi_read_timeout 150;
fastcgi_buffer_size 32k;
fastcgi_buffers 4 32k;
fastcgi_busy_buffers_size 64k;
fastcgi_temp_file_write_size 64k;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
server_names_hash_bucket_size 128;
client_header_buffer_size 64k;
large_client_header_buffers 4 128k;
client_max_body_size 8m;
client_body_timeout 3m;
client_header_timeout 3m;
gzip on;
gzip_disable "MSIE [1-6]\.";
gzip_comp_level 3;
gzip_buffers 4 8k;
gzip_min_length 1000;
gzip_types text/plain text/css application/x-javascript text/javascript;
#fastcgi_cache_path /data/webroot/php_cache levels=2:2
# keys_zone=PHP_CACHE:10m
# inactive=60m;
#fastcgi_temp_path /data/webroot/php_cache_tmp;
#fastcgi_cache_key "$scheme$request_method$host$uri";
#fastcgi_cache_use_stale error timeout invalid_header http_500;
#fastcgi_ignore_headers "Cache-Control" "Expires";
upstream fpmbalance {
server unix:/dev/shm/php-socket max_fails=3 fail_timeout=5;
server unix:/dev/shm/php-socket-2 max_fails=3 fail_timeout=5;
}
#limit_conn_zone $binary_remote_addr zone=one:10m;
#limit_req_zone $binary_remote_addr zone=onezone:10m rate=10r/s;
lua_package_path '/data/webroot/www/lua_api/lib/?.lua;/data/webroot/www/lua_api/?.lua;';
lua_package_cpath '/data/webroot/www/lua_api/lib/?.so;';
lua_shared_dict count 1M;
lua_shared_dict turl_map 100k;
lua_shared_dict turl_hit 100k;
lua_shared_dict sys_level 16k;
include /etc/nginx/sites-enabled/*;
}
server {
listen 80;
server_name www.myoverhaul.com;
server_tokens off;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
rewrite_log on;
access_log /var/log/nginx/myoverhaul.access.log;
error_log /var/log/nginx/myoverhaul.error.log notice;
location / {
root /data/webroot/www/overhaul;
index index.html;
#include /data/webroot/www/overhaul/.nginxaccess;
}
location ~* \.php {
fastcgi_pass unix:/dev/shm/php55-socket;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME /data/webroot/www/overhaul/$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
#! /bin/sh
### BEGIN INIT INFO
# Provides: php-fpm
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts php-fpm
# Description: starts the PHP FastCGI Process Manager daemon
### END INIT INFO
prefix=/usr/local/php-55
exec_prefix=${prefix}
php_fpm_BIN=${exec_prefix}/sbin/php-fpm
php_fpm_CONF=/etc/php/55/php-fpm.conf
php_fpm_PID=${prefix}/var/run/php-fpm.pid
php_opts="--fpm-config $php_fpm_CONF"
wait_for_pid () {
try=0
while test $try -lt 35 ; do
case "$1" in
'created')
if [ -f "$2" ] ; then
try=''
break
fi
;;
'removed')
if [ ! -f "$2" ] ; then
try=''
break
fi
;;
esac
echo -n .
try=`expr $try + 1`
sleep 1
done
}
case "$1" in
start)
echo -n "Starting php-fpm "
$php_fpm_BIN $php_opts
if [ "$?" != 0 ] ; then
echo " failed"
exit 1
fi
wait_for_pid created $php_fpm_PID
if [ -n "$try" ] ; then
echo " failed"
exit 1
else
echo " done"
fi
;;
stop)
echo -n "Gracefully shutting down php-fpm "
if [ ! -r $php_fpm_PID ] ; then
echo "warning, no pid file found - php-fpm is not running ?"
exit 1
fi
kill -QUIT `cat $php_fpm_PID`
wait_for_pid removed $php_fpm_PID
if [ -n "$try" ] ; then
echo " failed. Use force-quit"
exit 1
else
echo " done"
fi
;;
force-quit)
echo -n "Terminating php-fpm "
if [ ! -r $php_fpm_PID ] ; then
echo "warning, no pid file found - php-fpm is not running ?"
exit 1
fi
kill -TERM `cat $php_fpm_PID`
wait_for_pid removed $php_fpm_PID
if [ -n "$try" ] ; then
echo " failed"
exit 1
else
echo " done"
fi
;;
restart)
$0 stop
$0 start
;;
reload)
echo -n "Reload service php-fpm "
if [ ! -r $php_fpm_PID ] ; then
echo "warning, no pid file found - php-fpm is not running ?"
exit 1
fi
kill -USR2 `cat $php_fpm_PID`
echo " done"
;;
*)
echo "Usage: $0 {start|stop|force-quit|restart|reload}"
exit 1
;;
esac

Redis

1.Redis简介

redis是一个key-value存储系统。和Memcached类似,但是解决了断电后数据完全丢失的情况,而且她支持更多无化的value类型,除了和string外,还支持lists(链表)、sets(集合)和zsets(有序集合)几种数据类型。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。

2.Redis的性能

下面是官方的bench-mark数据:

  • The test was done with 50 simultaneous clients performing 100000 requests.

  • The value SET and GET is a 256 bytes string.

  • The Linux box is running Linux 2.6, it’s Xeon X3320 2.5Ghz.

  • Text executed using the loopback interface (127.0.0.1).

    Results: about 110000 SETs per second, about 81000 GETs per second.

更多详细数据请见官方bench-mark page(http://code.google.com/p/redis/wiki/Benchmarks

3.安装Redis

Redis的代码遵循ANSI-C编写,可以在所有POSIX系统(如Linux, *BSD, Mac OS X, Solaris等)上安装运行。而且Redis并不依赖任何非标准库,也没有编译参数必需添加。redis的安装出奇的简单,这可能也是他风靡的一个原因,让人很容易上手,不像某些东西,编译阶段就能让人完全绝望。

先去官网下载源码:

wget http://download.redis.io/releases/redis-stable.tar.gz

解压:

tar –zxvf redis-stable.tar.gz

编译

需要说明的事,redis的安装非常简单,已经有现成的Makefile文件,直接运行make命令即可。

make

make install

Redis 由四个可执行文件:redis-benchmarkredis-cliredis-serverredis-stat 这四个文件,加上一个redis.conf就构成了整个redis的最终可用包。它们的作用如下:

  • redis-server:Redis服务器的daemon启动程序
  • redis-cli:Redis命令行操作工具。当然,你也可以用telnet根据其纯文本协议来操作
  • redis-benchmark:Redis性能测试工具,测试Redis在你的系统及你的配置下的读写性能
  • redis-stat:Redis状态检测工具,可以检测Redis当前状态参数及延迟状况

现在就可以启动redis了,redis只有一个启动参数,就是他的配置文件路径。

redis-server /etc/redis.conf

注意,默认复制过去的redis.conf文件的daemonize参数为no,所以redis不会在后台运行,这时要测试,我们需要重新开一个终端。修改为yes则为后台运行redis。另外配置文件中规定了pid文件,log文件和数据文件的地址,如果有需要先修改,默认log信息定向到stdout.

下面是redis.conf的主要配置参数的意义:

  • daemonize:是否以后台daemon方式运行
  • pidfile:pid文件位置
  • port:监听的端口号
  • timeout:请求超时时间
  • loglevel:log信息级别
  • logfile:log文件位置
  • databases:开启数据库的数量
  • save * :保存快照的频率,第一个表示多长时间,第三个*表示执行多少次写操作。在一定时间内执行一定数量的写操作时,自动保存快照。可设置多个条件。
  • rdbcompression:是否使用压缩
  • dbfilename:数据快照文件名(只是文件名,不包括目录)
  • dir:数据快照的保存目录(这个是目录)
  • appendonly:是否开启appendonlylog,开启的话每次写操作会记一条log,这会提高数据抗风险能力,但影响效率。
  • appendfsync:appendonlylog如何同步到磁盘(三个选项,分别是每次写都强制调用fsync、每秒启用一次fsync、不调用fsync等待系统自己同步)

这时你可以打开一个终端进行测试了,配置文件中默认的监听端口是6379

我们可以开启一个Redis客户端进行测试

[root@SNDA-192-168-1-114 ~]# redis-cli  Could not connect to Redis at 127.0.0.1:6379: Connection refused  not connected> exit  [root@SNDA-192-168-1-114 ~]# redis-server /etc/redis.conf  [root@SNDA-192-168-1-114 ~]# redis-cli  redis 127.0.0.1:6379> quit

4.redis数据结构

redis 的作者antirez曾称其为一个数据结构服务器(data structures server),这是一个非常准确的表述,redis的所有功能就是将数据以其固有的几种结构保存,并提供给用户操作这几种结构的接口。我们可以想象我们在各种语言中的那些固有数据类型及其操作。

redis目前提供四种数据类型:string,list,setzset(sorted set)和Hash

  • string是最简单的类型,你可以理解成与Memcached一模一个的类型,一个key对应一个value,其上支持的操作与Memcached的操作类似。但它的功能更丰富。
  • list是一个链表结构,主要功能是push、pop、获取一个范围的所有值等等。操作中key理解为链表的名字。
  • set是集合,和我们数学中的集合概念相似,对集合的操作有添加删除元素,有对多个集合求交并差等操作。操作中key理解为集合的名字。
  • zset是set的一个升级版本,他在set的基础上增加了一个顺序属性,这一属性在添加修改元素的时候可以指定,每次指定后,zset会自动重新按新的值调整顺序。可以理解了有两列的mysql表,一列存value,一列存顺序。操作中key理解为zset的名字。
  • Hash数据类型允许用户用Redis存储对象类型,Hash数据类型的一个重要优点是,当你存储的数据对象只有很少几个key值时,数据存储的内存消耗会很小.更多关于Hash数据类型的说明请见: http://code.google.com/p/redis/wiki/Hashes

在官网上给出了所有支持的接口列表,并副副附有详细的介绍,地址:

http://code.google.com/p/redis/wiki/CommandReference

另外,作者还提供了一个非常贴心的web命令行模拟页面,供初学者试用redis,地址:

http://try.redis-db.com/

5.redis数据存储

redis的存储分为内存存储、磁盘存储和log文件三部分,配置文件中有三个参数对其进行配置。

save seconds updatessave配置,指出在多长时间内,有多少次更新操作,就将数据同步到数据文件。这个可以多个条件配合,比如默认配置文件中的设置,就设置了三个条件。

appendonly yes/**no **,appendonly配置,指出是否在每次更新操作后进行日志记录,如果不开启,可能会在断电时导致一段时间内的数据丢失。因为redis本身同步数据文件是按上面的save条件来同步的,所以有的数据会在一段时间内只存在于内存中。

appendfsync no/always/everysec ,appendfsync配置,no表示等操作系统进行数据缓存同步到磁盘,always表示每次更新操作后手动调用fsync()将数据写到磁盘,everysec表示每秒同步一次。

6.Redis Cluster 搭建与使用

Redis Cluster终于出了Stable,这让人很是激动,等Stable很久了,所以还是先玩玩。

####6.1. 集群简单概念。

Redis 集群是一个可以在多个 Redis 节点之间进行数据共享的设施(installation)。

Redis 集群不支持那些需要同时处理多个键的 Redis 命令, 因为执行这些命令需要在多个 Redis 节点之间移动数据, 并且在高负载的情况下, 这些命令将降低 Redis 集群的性能, 并导致不可预测的行为。

Redis 集群通过分区(partition)来提供一定程度的可用性(availability): 即使集群中有一部分节点失效或者无法进行通讯, 集群也可以继续处理命令请求。

Redis 集群提供了以下两个好处:

  • 将数据自动切分(split)到多个节点的能力。
  • 当集群中的一部分节点失效或者无法进行通讯时, 仍然可以继续处理命令请求的能力。

Redis 集群使用数据分片(sharding)而非一致性哈希(consistency hashing)来实现: 一个 Redis 集群包含 16384 个哈希槽(hash slot), 数据库中的每个键都属于这 16384 个哈希槽的其中一个, 集群使用公式 CRC16(key) % 16384 来计算键 key 属于哪个槽, 其中 CRC16(key) 语句用于计算键 key 的 CRC16 校验和 。

集群中的每个节点负责处理一部分哈希槽。 举个例子, 一个集群可以有三个哈希槽, 其中:

  • 节点 A 负责处理 0 号至 5500 号哈希槽。
  • 节点 B 负责处理 5501 号至 11000 号哈希槽。
  • 节点 C 负责处理 11001 号至 16384 号哈希槽。

这种将哈希槽分布到不同节点的做法使得用户可以很容易地向集群中添加或者删除节点。 比如说:

  • 如果用户将新节点 D 添加到集群中, 那么集群只需要将节点 A 、B 、 C 中的某些槽移动到节点 D 就可以了。
  • 与此类似, 如果用户要从集群中移除节点 A , 那么集群只需要将节点 A 中的所有哈希槽移动到节点 B 和节点 C , 然后再移除空白(不包含任何哈希槽)的节点 A 就可以了。

因为将一个哈希槽从一个节点移动到另一个节点不会造成节点阻塞, 所以无论是添加新节点还是移除已存在节点, 又或者改变某个节点包含的哈希槽数量, 都不会造成集群下线。

为了使得集群在一部分节点下线或者无法与集群的大多数(majority)节点进行通讯的情况下, 仍然可以正常运作, Redis 集群对节点使用了主从复制功能: 集群中的每个节点都有 1 个至 N 个复制品(replica), 其中一个复制品为主节点(master), 而其余的 N-1 个复制品为从节点(slave)。

在之前列举的节点 A 、B 、C 的例子中, 如果节点 B 下线了, 那么集群将无法正常运行, 因为集群找不到节点来处理 5501 号至 11000号的哈希槽。

另一方面, 假如在创建集群的时候(或者至少在节点 B 下线之前), 我们为主节点 B 添加了从节点 B1 , 那么当主节点 B 下线的时候, 集群就会将 B1 设置为新的主节点, 并让它代替下线的主节点 B , 继续处理 5501 号至 11000 号的哈希槽, 这样集群就不会因为主节点 B 的下线而无法正常运作了。

不过如果节点 B 和 B1 都下线的话, Redis 集群还是会停止运作。

Redis-cluster 架构图如下:

img

 

架构细节:

(1)所有的redis节点彼此互联(PING-PONG机制),内部使用二进制协议优化传输速度和带宽.

(2)节点的fail是通过集群中超过半数的节点检测失效时才生效.

(3)客户端与redis节点直连,不需要中间proxy层.客户端不需要连接集群所有节点,连接集群中任何一个可用节点即可

(4)redis-cluster把所有的物理节点映射到[0-16383]slot上,cluster 负责维护node<->slot<->value

 

二. Redis Cluster搭建使用

要让集群正常工作至少需要3个主节点,在这里我们要创建6个redis节点,其中三个为主节点,三个为从节点,对应的redis节点的ip和端口对应关系如下(为了简单演示都在同一台机器上面)

127.0.0.1:7000 127.0.0.1:7001

127.0.0.1:7002

127.0.0.1:7003

127.0.0.1:7004

127.0.0.1:7005

\1. 下载最新版redis。

wget http://download.redis.io/releases/redis-3.0.0.tar.gz

\2. 解压,安装

tar xf redis-3.0.0.tar.gz                       
cd redis-3.0.0
make && make install

3.创建存放多个实例的目录

mkdir /data/cluster -p
cd /data/cluster
mkdir 7000 7001 7002 7003 7004 7005

4.修改配置文件

cp redis-3.0.0/redis.conf /data/cluster/7000/

修改配置文件中下面选项

port 7000

daemonize yes

cluster-enabled yes

cluster-config-file nodes.conf

cluster-node-timeout 5000

appendonly yes

文件中的 cluster-enabled 选项用于开实例的集群模式, 而 cluster-conf-file 选项则设定了保存节点配置文件的路径, 默认值为nodes.conf 。其他参数相信童鞋们都知道。节点配置文件无须人为修改, 它由 Redis 集群在启动时创建, 并在有需要时自动进行更新。

修改完成后,把修改完成的redis.conf复制到7001-7005目录下,并且端口修改成和文件夹对应。

5.分别启动6个redis实例。

复制代码

cd /data/cluster/7000
redis-server redis.conf
cd /data/cluster/7001
redis-server redis.conf
cd /data/cluster/7002
redis-server redis.conf
cd /data/cluster/7003
redis-server redis.conf
cd /data/cluster/7004
redis-server redis.conf
cd /data/cluster/7005
redis-server redis.conf

复制代码

查看进程否存在。

复制代码

[root@redis-server 7005]# ps -ef | grep redis
root      4168     1  0 11:49 ?        00:00:00 redis-server *:7000 [cluster]
root      4176     1  0 11:49 ?        00:00:00 redis-server *:7001 [cluster]
root      4186     1  0 11:50 ?        00:00:00 redis-server *:7002 [cluster]
root      4194     1  0 11:50 ?        00:00:00 redis-server *:7003 [cluster]
root      4202     1  0 11:50 ?        00:00:00 redis-server *:7004 [cluster]
root      4210     1  0 11:50 ?        00:00:00 redis-server *:7005 [cluster]
root      4219  4075  0 11:50 pts/2    00:00:00 grep redis

复制代码

6.执行命令创建集群,首先安装依赖,否则创建集群失败。

yum install ruby rubygems -y

安装gem-redis

下载地址:https://rubygems.org/gems/redis/versions/3.0.0

gem install -l redis-3.0.0.gem  

复制集群管理程序到/usr/local/bin

cp redis-3.0.0/src/redis-trib.rb /usr/local/bin/redis-trib 

创建集群:

redis-trib create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005

命令的意义如下:

  • 给定 redis-trib.rb 程序的命令是 create , 这表示我们希望创建一个新的集群。
  • 选项 --replicas 1 表示我们希望为集群中的每个主节点创建一个从节点。
  • 之后跟着的其他参数则是实例的地址列表, 我们希望程序使用这些地址所指示的实例来创建新集群。

简单来说, 以上命令的意思就是让 redis-trib 程序创建一个包含三个主节点和三个从节点的集群。

接着, redis-trib 会打印出一份预想中的配置给你看, 如果你觉得没问题的话, 就可以输入 yes , redis-trib 就会将这份配置应用到集群当中:

复制代码

>>> Creating cluster
Connecting to node 127.0.0.1:7000: OK
Connecting to node 127.0.0.1:7001: OK
Connecting to node 127.0.0.1:7002: OK
Connecting to node 127.0.0.1:7003: OK
Connecting to node 127.0.0.1:7004: OK
Connecting to node 127.0.0.1:7005: OK
>>> Performing hash slots allocation on 6 nodes...
Using 3 masters:
127.0.0.1:7000
127.0.0.1:7001
127.0.0.1:7002
Adding replica 127.0.0.1:7003 to 127.0.0.1:7000
Adding replica 127.0.0.1:7004 to 127.0.0.1:7001
Adding replica 127.0.0.1:7005 to 127.0.0.1:7002
M: 2774f156af482b4f76a5c0bda8ec561a8a1719c2 127.0.0.1:7000
   slots:0-5460 (5461 slots) master
M: 2d03b862083ee1b1785dba5db2987739cf3a80eb 127.0.0.1:7001
   slots:5461-10922 (5462 slots) master
M: 0456869a2c2359c3e06e065a09de86df2e3135ac 127.0.0.1:7002
   slots:10923-16383 (5461 slots) master
S: 37b251500385929d5c54a005809377681b95ca90 127.0.0.1:7003
   replicates 2774f156af482b4f76a5c0bda8ec561a8a1719c2
S: e2e2e692c40fc34f700762d1fe3a8df94816a062 127.0.0.1:7004
   replicates 2d03b862083ee1b1785dba5db2987739cf3a80eb
S: 9923235f8f2b2587407350b1d8b887a7a59de8db 127.0.0.1:7005
   replicates 0456869a2c2359c3e06e065a09de86df2e3135ac
Can I set the above configuration? (type 'yes' to accept): 

复制代码

输入 yes 并按下回车确认之后, 集群就会将配置应用到各个节点, 并连接起(join)各个节点 —— 也即是, 让各个节点开始互相通讯:

复制代码

Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join......
>>> Performing Cluster Check (using node 127.0.0.1:7000)
M: 2774f156af482b4f76a5c0bda8ec561a8a1719c2 127.0.0.1:7000
   slots:0-5460 (5461 slots) master
M: 2d03b862083ee1b1785dba5db2987739cf3a80eb 127.0.0.1:7001
   slots:5461-10922 (5462 slots) master
M: 0456869a2c2359c3e06e065a09de86df2e3135ac 127.0.0.1:7002
   slots:10923-16383 (5461 slots) master
M: 37b251500385929d5c54a005809377681b95ca90 127.0.0.1:7003
   slots: (0 slots) master
   replicates 2774f156af482b4f76a5c0bda8ec561a8a1719c2
M: e2e2e692c40fc34f700762d1fe3a8df94816a062 127.0.0.1:7004
   slots: (0 slots) master
   replicates 2d03b862083ee1b1785dba5db2987739cf3a80eb
M: 9923235f8f2b2587407350b1d8b887a7a59de8db 127.0.0.1:7005
   slots: (0 slots) master
   replicates 0456869a2c2359c3e06e065a09de86df2e3135ac
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

复制代码

一切正常输出以下信息:

[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

集群的客户端

Redis 集群现阶段的一个问题是客户端实现很少。 以下是一些我知道的实现:

  • redis-rb-cluster 是我(@antirez)编写的 Ruby 实现, 用于作为其他实现的参考。 该实现是对 redis-rb 的一个简单包装, 高效地实现了与集群进行通讯所需的最少语义(semantic)。
  • redis-py-cluster 看上去是 redis-rb-cluster 的一个 Python 版本, 这个项目有一段时间没有更新了(最后一次提交是在六个月之前), 不过可以将这个项目用作学习集群的起点。
  • 流行的 Predis 曾经对早期的 Redis 集群有过一定的支持, 但我不确定它对集群的支持是否完整, 也不清楚它是否和最新版本的 Redis 集群兼容 (因为新版的 Redis 集群将槽的数量从 4k 改为 16k 了)。
  • Redis unstable 分支中的 redis-cli 程序实现了非常基本的集群支持, 可以使用命令 redis-cli -c 来启动。

测试 Redis 集群比较简单的办法就是使用 redis-rb-cluster 或者 redis-cli , 接下来我们将使用 redis-cli 为例来进行演示:

[root@redis-server ~]# redis-cli -c -p 7001
127.0.0.1:7001> set name yayun
OK
127.0.0.1:7001> get name
"yayun"
127.0.0.1:7001> 

我们可以看看还有哪些命令可以用:

复制代码

[root@redis-server ~]# redis-trib help
Usage: redis-trib <command> <options> <arguments ...>

  set-timeout     host:port milliseconds
  add-node        new_host:new_port existing_host:existing_port
                  --master-id <arg>
                  --slave
  fix             host:port
  help            (show this help)
  del-node        host:port node_id
  import          host:port
                  --from <arg>
  check           host:port
  call            host:port command arg arg .. arg
  create          host1:port1 ... hostN:portN
                  --replicas <arg>
  reshard         host:port
                  --yes
                  --to <arg>
                  --from <arg>
                  --slots <arg>

For check, fix, reshard, del-node, set-timeout you can specify the host and port of any working node in the cluster.
[root@redis-server ~]# 

复制代码

可以看见有add-node,不用想了,肯定是添加节点。那么del-node就是删除节点。还有check肯定就是检查状态了。

复制代码

[root@redis-server ~]#  redis-cli -p 7000 cluster nodes 
2d03b862083ee1b1785dba5db2987739cf3a80eb 127.0.0.1:7001 master - 0 1428293673322 2 connected 5461-10922
37b251500385929d5c54a005809377681b95ca90 127.0.0.1:7003 slave 2774f156af482b4f76a5c0bda8ec561a8a1719c2 0 1428293672305 4 connected
e2e2e692c40fc34f700762d1fe3a8df94816a062 127.0.0.1:7004 slave 2d03b862083ee1b1785dba5db2987739cf3a80eb 0 1428293674340 5 connected
0456869a2c2359c3e06e065a09de86df2e3135ac 127.0.0.1:7002 master - 0 1428293670262 3 connected 10923-16383
2774f156af482b4f76a5c0bda8ec561a8a1719c2 127.0.0.1:7000 myself,master - 0 0 1 connected 0-5460
9923235f8f2b2587407350b1d8b887a7a59de8db 127.0.0.1:7005 slave 0456869a2c2359c3e06e065a09de86df2e3135ac 0 1428293675362 6 connected
[root@redis-server ~]# 

复制代码

可以看到7000-7002是master,7003-7005是slave。

故障转移测试:

127.0.0.1:7001> KEYS *
1) "name"
127.0.0.1:7001> get name
"yayun"
127.0.0.1:7001> 

可以看见7001是正常的,并且获取到了key,value,现在kill掉7000实例,再进行查询。

复制代码

[root@redis-server ~]# ps -ef | grep 7000
root      4168     1  0 11:49 ?        00:00:03 redis-server *:7000 [cluster]
root      4385  4361  0 12:39 pts/3    00:00:00 grep 7000
[root@redis-server ~]# kill 4168
[root@redis-server ~]# ps -ef | grep 7000
root      4387  4361  0 12:39 pts/3    00:00:00 grep 7000
[root@redis-server ~]# redis-cli -c -p 7001
127.0.0.1:7001> get name
"yayun"
127.0.0.1:7001> 

复制代码

可以正常获取到value,现在看看状态。

复制代码

[root@redis-server ~]# redis-cli -c -p 7001 cluster nodes
2d03b862083ee1b1785dba5db2987739cf3a80eb 127.0.0.1:7001 myself,master - 0 0 2 connected 5461-10922
0456869a2c2359c3e06e065a09de86df2e3135ac 127.0.0.1:7002 master - 0 1428295271619 3 connected 10923-16383
37b251500385929d5c54a005809377681b95ca90 127.0.0.1:7003 master - 0 1428295270603 7 connected 0-5460
e2e2e692c40fc34f700762d1fe3a8df94816a062 127.0.0.1:7004 slave 2d03b862083ee1b1785dba5db2987739cf3a80eb 0 1428295272642 5 connected
2774f156af482b4f76a5c0bda8ec561a8a1719c2 127.0.0.1:7000 master,fail - 1428295159553 1428295157205 1 disconnected
9923235f8f2b2587407350b1d8b887a7a59de8db 127.0.0.1:7005 slave 0456869a2c2359c3e06e065a09de86df2e3135ac 0 1428295269587 6 connected
[root@redis-server ~]# 

复制代码

原来的7000端口实例已经显示fail,原来的7003是slave,现在自动提升为master。

关于更多的在线添加节点,删除节点,以及对集群进行重新分片请参考官方文档。

总结:

redis-cluster是个好东西,只是stable才出来不久,肯定坑略多,而且现在使用的人比较少,前期了解学习一下是可以的,生产环境肯定要慎重考虑。且需要进行严格的测试。生产环境中redis的集群可以考虑使用Twitter开源的twemproxy,以及豌豆荚开源的codis,这两个项目都比较成熟,现在使用的公司很多。已经向业界朋友得到证实。后面也会写博客介绍twemproxy和codis。

参考资料:

http://redis.readthedocs.org/en/latest/topic/cluster-tutorial.html

http://hot66hot.iteye.com/blog/2050676

常用工具

##zsh 目前常用的 Linux 系统和 OS X 系统的默认 Shell 都是 bash,但是真正强大的 Shell 是深藏不露的 zsh, 这货绝对是马车中的跑车,跑车中的飞行车,史称『终极 Shell』,但是由于配置过于复杂,所以初期无人问津,很多人跑过来看看 zsh 的配置指南,什么都不说转身就走了。直到有一天,国外有个穷极无聊的程序员开发出了一个能够让你快速上手的zsh项目,叫做「oh my zsh」,Github 网址是:https://github.com/robbyrussell/oh-my-zsh。这玩意就像「X天叫你学会 C++」系列,可以让你神功速成,而且是真的。(引用自MacTalk-池建强的随想录

oh-my-zsh github网址:https://github.com/robbyrussell/oh-my-zsh oh-my-zsh 主题网址:https://github.com/robbyrussell/oh-my-zsh/wiki/Themes

###安装

sudo yum install zsh

###将shell切到zsh

chsh -s /bin/zsh

###安装oh my zsh 首先安装 git,安装方式同上,把 zsh 换成 git 即可。

安装「oh my zsh」可以自动安装也可以手动安装。

自动安装:

  wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sh

手动安装:​ git clone git://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh

cp ~/.oh-my-zsh/templates/zshrc.zsh-template ~/.zshrc

使用 Vagrant 打造跨平台开发环境

Vagrant是一款用来构建虚拟开发环境的工具,非常适合 php/python/ruby/java 这类语言开发 web 应用,我们可以通过 Vagrant 封装一个 Linux 的开发环境,分发给团队成员。成员可以在自己喜欢的桌面系统(Mac/Windows/Linux)上开发程序,代码却能统一在封装好的环境里运行。

安装步骤

1. 安装 VirtualBox

虚拟机还是得依靠 VirtualBox 来搭建,免费小巧。  下载地址:https://www.virtualbox.org/wiki/Downloads

2. 安装 Vagrant 并添加镜像

下载box镜像 ,下载成功后,在开发目录运行

$ vagrant box add hahaha ~/box/package.box  # 添加 package.box 镜像并命名为 hahaha
$ cd ~/dev  # 切换到项目目录
$ vagrant init hahaha  # 用 hahaha 镜像初始化。

3.常用命令

$ vagrant init  # 初始化
$ vagrant up  # 启动虚拟机
$ vagrant halt  # 关闭虚拟机
$ vagrant reload  # 重启虚拟机
$ vagrant ssh  # SSH 至虚拟机
$ vagrant status  # 查看虚拟机运行状态
$ vagrant destroy  # 销毁当前虚拟机
$ vagrant package #打包分发

4.修改配置

Vagrant 初始化成功后,会在初始化的目录里生成一个 Vagrantfile 的配置文件,可以修改配置文件进行个性化的定制。

Vagrant 默认是使用端口映射方式将虚拟机的端口映射本地从而实现类似 http://localhost:80 这种访问方式,这种方式比较麻烦,新开和修改端口的时候都得编辑。相比较而言,host-only 模式显得方便多了。打开 Vagrantfile,将下面这行的注释去掉(移除#)并保存:

config.vm.network :private_network, ip: "192.168.33.10"

重启虚拟机,这样我们就能用 192.168.33.10 访问这台机器了,你可以把 IP 改成其他地址,只要不产生冲突就行。

默认映射的目录为:Vagrantfile所在的目录, 移除下面#,修改到自己要映射到的目录

# config.vm.synced_folder "../data", "/vagrant_data"

修改完成后 vagrant reload 重载虚拟机

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment