Linux之搭建memcache缓存服务器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux之搭建memcache缓存服务器相关的知识,希望对你有一定的参考价值。

Linux之搭建memcache缓存服务器(nginx+php+memcache+mysql)

二、centos7.2+nginx+php+memcache+mysql

环境描述:

OS

[[email protected] ~]# cat /etc/redhat-release

CentOS Linux release 7.2.1511 (Core)

nginxphp

nginx-1.10.2.tar.gz

php-5.6.27.tar.gz

ip地址:192.168.31.141/24

memcache:

memcached-1.4.33.tar.gz

ip地址:192.168.31.250/24

mysql:

mysql-5.7.13.tar.gz

ip地址:192.168.31.225/24

1、安装nginx(192.168.31.141主机操作)

解压zlib

[[email protected] ~]# tar zxf zlib-1.2.8.tar.gz

说明:不需要编译,只需要解压就行。

解压pcre

[[email protected] ~]# tar zxf pcre-8.39.tar.gz

说明:不需要编译,只需要解压就行。

[[email protected] ~]# yum -y install gcc gcc-c++ make libtool openssl openssl-devel

下载nginx的源码包:http://nginx.org/download

解压源码包:

[[email protected] ~]# tar zxf nginx-1.10.2.tar.gz

[[email protected] ~]# cd nginx-1.10.2/

 [[email protected] ~]# groupadd www   #添加www

[[email protected] ~]# useradd -g www www -s /sbin/nologin  #创建nginx运行账户www并加入到www组,不允许www用户直接登录系统

[[email protected] nginx-1.10.2]# ./configure --prefix=/usr/local/nginx1.10 --with-http_dav_module --with-http_stub_status_module --with-http_addition_module --with-http_sub_module  --with-http_flv_module --with-http_mp4_module --with-pcre=/root/pcre-8.39 --with-zlib=/root/zlib-1.2.8 --with-http_ssl_module --with-http_gzip_static_module --user=www --group=www

[[email protected] nginx-1.10.2]# make&& make install

注:

--with-pcre:用来设置pcre源码目录。
 --with-zlib:用来设置zlib源码目录。
 因为编译nginx需要用到这两个库的源码。

[[email protected] nginx-1.10.2]# ln -s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/

[[email protected] nginx-1.10.2]# nginx -t

启动nginx

[[email protected] nginx-1.10.2]# nginx

[[email protected] nginx-1.10.2]# netstat -anpt | grep nginx

tcp   0   0 0.0.0.0:80     0.0.0.0:*    LISTEN      9834/nginx: master

[[email protected] nginx-1.10.2]# firewall-cmd --permanent --add-port=80/tcp

success

[[email protected] nginx-1.10.2]# firewall-cmd --reload

success

启动后可以再浏览器中打开页面,会显示nginx默认页面。

技术分享

2、安装php

安装libmcrypt

[[email protected] ~]# tar zxf libmcrypt-2.5.7.tar.gz

[[email protected] ~]# cd libmcrypt-2.5.7/

[[email protected] libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install

[[email protected] ~]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel

[[email protected] ~]# tar zxf php-5.6.27.tar.gz

[[email protected] ~]# cd php-5.6.27/

[[email protected] php-5.6.27]#./configure --prefix=/usr/local/php5.6 --with-mysql=mysqlnd --with-pdo-mysql=mysqlnd --with-mysqli=mysqlnd --with-openssl --enable-fpm --enable-sockets --enable-sysvshm --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --with-mhash --with-mcrypt=/usr/local/libmcrypt --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --enable-maintainer-zts

[[email protected] php-5.6.27]# make&& make install

[[email protected] php-5.6.27]# cp php.ini-production /etc/php.ini

修改/etc/php.ini文件,将short_open_tag修改为on,修改后的内容如下:

short_open_tag = On //支持php短标签

创建php-fpm服务启动脚本:

[[email protected] php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm

[[email protected] php-5.6.27]# chmod +x /etc/init.d/php-fpm

[[email protected] php-5.6.27]# chkconfig --add php-fpm

[[email protected] php-5.6.27]# chkconfig php-fpm on

提供php-fpm配置文件并编辑:

#cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf

[[email protected] php-5.6.27]# vi /usr/local/php5.6/etc/php-fpm.conf

修改内容如下:

pid = run/php-fpm.pid

listen =127.0.0.1:9000

pm.max_children = 300

pm.start_servers = 10

pm.min_spare_servers = 10

pm.max_spare_servers =50

启动php-fpm服务:

[[email protected] ~]# service  php-fpm start

Starting php-fpm  done

[[email protected] php-5.6.27]# netstat -anpt | grep php-fpm

tcp   0   0 127.0.0.1:9000    0.0.0.0:*     LISTEN      10937/php-fpm: mast

3、安装mysql(在192.168.31.225主机操作)

因为centos7.2默认安装了mariadb-libs,所以先要卸载掉

查看是否安装mariadb

#rpm -qa | grep mariadb

卸载mariadb

rpm -e --nodeps mariadb-libs

技术分享

2安装依赖包

注: 相关依赖包的作用

cmake由于从MySQL5.5版本开始弃用了常规的configure编译方法,所以需要CMake编译器,用于设置mysql的编译参数。如:安装目录、数据存放目录、字符编码、排序规则等。

Boost  #MySQL 5.7.5开始Boost库是必需的,mysql源码中用到了C++Boost库,要求必须安装boost1.59.0或以上版本

GCCLinux下的C语言编译工具,mysql源码编译完全由CC++编写,要求必须安装GCC

bisonLinuxC/C++语法分析器

ncurses字符终端处理库

1安装文件准备

下载cmake-3.5.tar.gz    http://wwwNaNake.org/download/

下载ncurses-5.9.tar.gzftp://ftp.gnu.org/gnu/ncurses/

下载bison-3.0.4.tar.gzhttp://ftp.gnu.org/gnu/bison/

下载mysql-5.7.13.tar.gz

wget http://cdn.mysql.com/Downloads/MySQL-5.7/mysql-5.7.13.tar.gz

下载Boost_1_59_0.tar.gz

wget http://nchc.dl.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.gz

2安装CMAKE及必要的软件

安装cmake

技术分享

技术分享

cmake –version  ---查看cmake版本

技术分享

安装ncurses


技术分享

安装bison

技术分享

安装bootst

tar zxf  boost_1_59_0.tar.gz

mv boost_1_59_0 /usr/local/boost

3创建mysql用户和用户组及目录

# groupadd -r mysql && useradd -r -g mysql -s /bin/false -M mysql---新建msyql组和msyql用户禁止登录shell

#mkdir /usr/local/mysql        ---创建目录

#mkdir /usr/local/mysql/data    ---数据库目录

3、编译安装mysql

解压mysql源码包:

技术分享

执行cmake命令进行编译前的配置:

技术分享

开始编译、编译安装

技术分享

1:配置解释:

-DCMAKE_INSTALL_PREFIX=/usr/local/mysql[MySQL安装的根目录]-DMYSQL_DATADIR=/usr/local/mysql /data[MySQL数据库文件存放目录]

-DSYSCONFDIR=/etc [MySQL配置文件所在目录]

-DWITH_MYISAM_STORAGE_ENGINE=1 [添加MYISAM引擎支持]

-DWITH_INNOBASE_STORAGE_ENGINE=1[添加InnoDB引擎支持]

-DWITH_ARCHIVE_STORAGE_ENGINE=1  [添加ARCHIVE引擎支持]

-DMYSQL_UNIX_ADDR=/usr/local/mysql /mysql.sock[指定mysql.sock位置]

-DWITH_PARTITION_STORAGE_ENGINE=1[安装支持数据库分区]

-DEXTRA_CHARSETS=all [使MySQL支持所有的扩展字符]

-DDEFAULT_CHARSET=utf8[设置MySQL的默认字符集为utf8]-DDEFAULT_COLLATION=utf8_general_ci [设置默认字符集校对规则]

-DWITH-SYSTEMD=1  [可以使用systemd控制mysql服务]

-DWITH_BOOST=/usr/local/boost  [指向boost库所在目录]

更多参数执行[[email protected] mysql-5.7.13]# cmake . –LH

2:为了加快编译速度可以按下面的方式编译安装

技术分享

make -j $(grep processor /proc/cpuinfo | wc –l)

-j参数表示根据CPU核数指定编译时的线程数,可以加快编译速度。默认为1个线程编译。

3:若要重新运行cmake配置,需要删除CMakeCache.txt文件

# make clean

#rm -f CMakeCache.txt

优化Mysql的执行路径

技术分享

4设置权限并初始化MySQL系统授权表

# cd/usr/local/mysql

# chown -R mysql:mysql  .       ---更改所有者,属组,注意是mysql .

#bin/mysqld --initialize--user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data  

1root初始化操作时要加--user=mysql参数,生成一个随机密码(注意保存登录时用)

2MySQL 5.7.6之前的版本执行这个脚本初始化系统数据库

/usr/local/mysql/bin/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

# 5.7.6之后版本初始系统数据库脚本(本文使用此方式初始化)

#/usr/local/mysql/bin/mysqld --initialize-insecure--user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

技术分享

注意:如果使用–initialize参数初始化系统数据库之后,会生成root用户的一个临时密码,如高亮中所示

# chown -Rmysql:mysql .       ---改所有者,注意是root .

5、创建配置文件

# cd/usr/local/mysql/support-files     ---进入MySQL安装目录支持文件目录

# cp my-default.cnf /etc/my.cnf    ---复制模板为新的配置文件,

技术分享

修改文件中配置选项,如下图所示,添加如下配置项

#vi  /etc/my.cnf

技术分享

6配置mysql自动启动

技术分享

技术分享

服务启动失败,查看错误日志文件

技术分享

mysqld.service,把默认的pid文件指定到了/var/run/mysqld/目录,而并没有事先建立该目录,因此要手动建立该目录并把权限赋给mysql用户。

技术分享

或者修改/usr/lib/system/system/mysqld.service,修改内容如下:

技术分享

#systemctl  daemon-reload

再次启动mysql服务

技术分享

查看端口号技术分享

服务启动成功

访问MySQL数据库

# mysql -u root -h 127.0.0.1 -p     ---连接mysql,输入初始化时生成的随机密码

技术分享

设置数据库管理员用户root的密码技术分享

4、安装memcached服务端(在192.168.31.250主机操作)

memcached是基于libevent的事件处理。libevent是个程序库,它将LinuxepollBSD类操作系统的kqueue等事件处理功能封装成统一的接口。即使对服务器的连接数增加,也能发挥I/O的性能。 memcached使用这个libevent库,因此能在LinuxBSDSolaris等操作系统上发挥其高性能。

首先先安装memcached依赖库libevent

[[email protected] ~]# tar zxf libevent-2.0.22-stable.tar.gz

[[email protected] ~]# cd libevent-2.0.22-stable/

[[email protected] libevent-2.0.22-stable]# ./configure

[[email protected] libevent-2.0.22-stable]# make&& make install

安装memcached

[[email protected] ~]# tar zxf memcached-1.4.33.tar.gz

[[email protected] ~]# cd memcached-1.4.33/

[[email protected] memcached-1.4.33]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local

[[email protected] memcached-1.4.33]# make&& make install

检测是否成功安装

[[email protected] ~]# ls /usr/local/memcached/bin/memcached

/usr/local/memcached/bin/memcached

通过以上操作就很简单的把memcached服务端编译好了。这时候就可以打开服务端进行工作了。

配置环境变量:
进入用户宿主目录,编辑.bash_profile,为系统环境变量LD_LIBRARY_PATH增加新的目录,需要增加的内容如下:

[[email protected] ~]# vi ~/.bash_profile

MEMCACHED_HOME=/usr/local/memcached

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MEMCACHED_HOME/lib

[[email protected] ~]# /usr/local/memcached/bin/memcached -d -m 2048 -l 192.168.31.250 -p 11211 -u root -c 10240 -P /usr/local/memcached /memcached.pid

启动参数说明:

-d  选项是启动一个守护进程。

-m  分配给Memcache使用的内存数量,单位是MB,默认64MB。

-l  监听的IP地址。(默认:INADDR_ANY,所有地址)

-p  设置Memcache的TCP监听的端口,最好是1024以上的端口。

-u  运行Memcache的用户,如果当前为root的话,需要使用此参数指定用户。

-c  选项是最大运行的并发连接数,默认是1024。

-P  设置保存Memcache的pid文件。

-M 内存耗尽时返回错误,而不是删除项

-f 块大小增长因子,默认是1.25
-n 最小分配空间,key+value+flags默认是48
-h 显示帮助

[[email protected] ~]# netstat -anpt |grep memcached

tcp   0  0 192.168.31.250:11211    0.0.0.0:*  LISTEN      12840/memcached

设置防火墙:

[[email protected] ~]# firewall-cmd --permanent --add-port=11211/tcp

success

[[email protected] ~]# firewall-cmd --reload

success

刷新用户环境变量:

[[email protected] ~]# source ~/.bash_profile

编写memcached服务启停脚本

[[email protected] ~]# vi /etc/init.d/memcached

脚本内容如下:

[[email protected] ~]# cat /etc/init.d/memcached

#!/bin/sh

#

# pidfile: /usr/local/memcached/memcached.pid

# memcached_home: /usr/local/memcached

# chkconfig: 35 21 79

# description: Start and stop memcached Service

 

# Source function library

. /etc/rc.d/init.d/functions

 

RETVAL=0

 

prog="memcached"

basedir=/usr/local/memcached

cmd=${basedir}/bin/memcached

pidfile="$basedir/${prog}.pid"

 

#interface to listen on (default: INADDR_ANY, all addresses)

ipaddr="192.168.31.250"

#listen port

port=11211

#username for memcached

username="root"

#max memory for memcached,default is 64M

max_memory=2048

#max connections for memcached

max_simul_conn=10240

start() {

echo -n $"Starting service: $prog"

$cmd -d -m $max_memory -u $username -l $ipaddr -p $port -c $max_simul_conn -P $pidfile

RETVAL=$?

echo

[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog

}

 

stop() {

echo -n $"Stopping service: $prog  "

run_user=$(whoami)

pidlist=$(ps -ef | grep $run_user | grep memcached | grep -v grep | awk ‘{print($2)}‘)

for pid in $pidlist

do

kill -9 $pid

if [ $? -ne 0 ]; then

return 1

fi

done

RETVAL=$?

echo

[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog

}

 

# See how we were called.

case "$1" in

start)

start

;;

stop)

stop

;;

restart)

stop

start

;;

*)

echo "Usage: $0 {start|stop|restart|status}"

exit 1

esac

exit $RETVAL

设置脚本可被执行:

[[email protected] ~]# chmod +x /etc/init.d/memcached

[[email protected] ~]# chkconfig --add memcached

[[email protected] ~]# chkconfig memcached on

说明:

shell脚本中return的作用

1)终止一个函数.
2)return命令允许带一个整型参数, 这个整数将作为函数的"退出状态
"返回给调用这个函数的脚本, 并且这个整数也被赋值给变量$?.
3)命令格式:return value

5、配置nginx.conf文件(在nginx主机操作)

配置内容如下:

user www www;

worker_processes  4;

worker_cpu_affinity 0001 0010 0100 1000;

error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

 

pid        logs/nginx.pid;

 

events {

use epoll;

    worker_connections  65535;

multi_accept on;

}

 

http {

include       mime.types;

    default_type  application/octet-stream;

 

    #log_format  main  ‘$remote_addr - $remote_user [$time_local] "$request" ‘

    #                  ‘$status $body_bytes_sent "$http_referer" ‘

    #                  ‘"$http_user_agent" "$http_x_forwarded_for"‘;

 

    #access_log  logs/access.log  main;

 

sendfile        on;

tcp_nopush     on;

    keepalive_timeout  65;

tcp_nodelay on;

client_header_buffer_size 4k;

open_file_cache max=102400 inactive=20s;

    open_file_cache_valid 30s;

    open_file_cache_min_uses 1;

    client_header_timeout 15;

    client_body_timeout 15;

reset_timedout_connection on;

    send_timeout 15;

server_tokens off;

client_max_body_size 10m;

 

    fastcgi_connect_timeout     600;

    fastcgi_send_timeout 600;

    fastcgi_read_timeout 600;

fastcgi_buffer_size 64k;

    fastcgi_buffers     4 64k;

fastcgi_busy_buffers_size 128k;

fastcgi_temp_file_write_size 128k;

    fastcgi_temp_path /usr/local/nginx1.10/nginx_tmp;

fastcgi_intercept_errors on;

    fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g;

 

gzip on;

    gzip_min_length  2k;

    gzip_buffers     4 32k;

    gzip_http_version 1.1;

    gzip_comp_level 6;

    gzip_types  text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;

gzip_vary on;

gzip_proxied any;

server {

listen       80;

        server_name  www.benet.com;

 

        #charset koi8-r;

 

        #access_log  logs/host.access.log  main;

 

location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {

valid_referers none blocked  www.benet.com benet.com;

if ($invalid_referer) {

                #return 302  http://www.benet.com/img/nolink.jpg;

return 404;

break;

             }

access_log off;

        }

location / {

root   html;

index  index.php index.html index.htm;

        }

location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {

expires 30d;

            #log_not_found off;

access_log off;

        }

 

location ~* \.(js|css)$ {

expires 7d;

log_not_found off;

access_log off;

        }      

 

location = /(favicon.ico|roboots.txt) {

access_log off;

log_not_found off;

        }

location /status {

stub_status on;

        }

location ~ .*\.(php|php5)?$ {

root html;

            fastcgi_pass 127.0.0.1:9000;

            fastcgi_index index.php;

include fastcgi.conf;

            #fastcgi_cache cache_fastcgi;

            fastcgi_cache_valid 200 302 1h;

            fastcgi_cache_valid 301 1d;

fastcgi_cache_valid any 1m;

            fastcgi_cache_min_uses 1;

fastcgi_cache_use_stale error timeout invalid_header http_500;

            fastcgi_cache_key http://$host$request_uri;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html

        #

        error_page   500 502 503 504  /50x.html;

location = /50x.html {

root   html;

        }

   }

}

重启nginx服务

生成一个php测试页

[[email protected] memcache-3.0.8]# cat /usr/local/nginx1.10/html/test1.php

<?php

phpinfo();

?>

使用浏览器访问test1.php测试页

技术分享

6memcache客户端(在php服务器操作):

memcache分为服务端和客户端。服务端用来存放缓存,客户端用来操作缓存。

安装php扩展库(phpmemcache)。

安装PHP Memcache扩展:

可以使用php自带的pecl安装程序
# /usr/local/php5.6/bin/pecl install memcache

也可以从源码安装,他是生成php的扩展库文件memcache.so

安装memcache扩展库

[[email protected] ~]# tar zxf memcache-3.0.8.tgz

[[email protected] ~]# cd memcache-3.0.8/

[[email protected] memcache-3.0.8]# /usr/local/php5.6/bin/phpize

[[email protected]]#./configure --enable-memcache --with-php-config=/usr/local/php5.6/bin/php-config

[[email protected] memcache-3.0.8]# make&& make install

安装完后会有类似这样的提示:

Installing shared extensions:     /usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/

把这个记住,然后修改php.ini

添加一行

extension=/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/memcache.so

重启php-fpm服务

[[email protected] memcache-3.0.8]# service  php-fpm restart

Gracefully shutting down php-fpm .done

Starting php-fpm  done

测试:

检查php扩展是否正确安装

1[[email protected] html]# /usr/local/php5.6/bin/php -m

命令行执行php -m 查询结果中是否有memcache

2创建phpinfo()页面,查询session项下面的Registered save handlers值中是否有memcache

浏览器访问test1.php

技术分享

技术分享

测试代码:

[[email protected] ~]# cat /usr/local/nginx1.10/html/test2.php

<?php

$memcache = new Memcache;

$memcache->connect(‘192.168.31.250‘, 11211) or die ("Could not connect");

$version = $memcache->getVersion();

echo "Server‘s version: ".$version."<br/>";

$tmp_object = new stdClass;

$tmp_object->str_attr = ‘test‘;

$tmp_object->int_attr = 123;

$memcache->set(‘key‘, $tmp_object, false, 10) or die ("Failed to save data at the server");

echo "Store data in the cache (data will expire in 10 seconds)<br/>";

$get_result = $memcache->get(‘key‘);

echo "Data from the cache:<br/>";

var_dump($get_result);

?>

浏览器访问test2.php

技术分享

使用memcache实现session共享

配置php.ini中的Sessionmemcache方式。

session.save_handler = memcache

session.save_path = "tcp://192.168.31.250:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

注:

session.save_handler设置session的储存方式为memcache 默认以文件方式存取session数据,如果想要使用自定义的处理来存取session数据,比如memcache方式则修为session.save_handler = memcache

session.save_path设置session储存的位置,多台memcache用逗号隔开

使用多个 memcached server 时用逗号”,”隔开,可以带额外的参数”persistent”、”weight”、”timeout”、”retry_interval”等等,
类似这样的:"tcp://host:port?persistent=1&weight=2,tcp://host2:port2"

memcache实现session共享也可以在某个一个应用中设置 
ini_set("session.save_handler", "memcache"); 
ini_set("session.save_path", "tcp://192.168.0.9:11211"); 

ini_set()只对当前php页面有效,并且不会去修改php.ini文件本身,也不会影响其他php页面。

测试memcache可用性

重启php-fpm

web服务器上新建//usr/local/nginx1.10/html/memcache.php文件。内容如

<?php

session_start();

if (!isset($_SESSION[‘session_time‘]))

{

 $_SESSION[‘session_time‘] = time();

}

echo "session_time:".$_SESSION[‘session_time‘]."<br />";

echo "now_time:".time()."<br />";

echo "session_id:".session_id()."<br />";

?>

访问网址http://192.168.31.141/memcache.php可以查看session_time是否都是为memcache中的Session,同时可以在不同的服务器上修改不同的标识查看是否为不同的服务器上的。

技术分享

可以直接用sessionid memcached 里查询一下:

[[email protected] html]# telnet 192.168.31.250 11211

Trying 192.168.31.250...

Connected to 192.168.31.250.

Escape character is ‘^]‘.

get ffaqe5b1oar311n3cn5q9co5g6

VALUE ffaqe5b1oar311n3cn5q9co5g6 0 26

session_time|i:1479134997;

得到session_time|i:1479134997;这样的结果,说明session 正常工作 

默认memcache会监听11221端口,如果想清空服务器上memecache的缓存,一般使用的是:
[[email protected] ~]# telnet 192.168.31.250 11211

Trying 192.168.31.250...

Connected to 192.168.31.250.

Escape character is ‘^]‘.

flush_all

OK

同样也可以使用:
[[email protected] ~]# echo "flush_all" | nc 192.168.31.250 11211

OK

使用flush_all 后并不是删除memcache上的key,而是置为过期

memcache安全配置

因为memcache不进行权限控制,因此需要通过iptablesmemcache仅开放个web服务器。

7、测试memcache缓存数据库数据

Mysql服务器上创建测试表

mysql> create database testdb1;

Query OK, 1 row affected (0.00 sec)

 

mysql> use testdb1;

Database changed

mysql> create table test1(id int not null auto_increment,name varchar(20) default null,primary key (id)) engine=innodb auto_increment=1 default charset=utf8;

Query OK, 0 rows affected (0.03 sec)

 

mysql> insert into test1(name) values (‘tom1‘),(‘tom2‘),(‘tom3‘),(‘tom4‘),(‘tom5‘);

Query OK, 5 rows affected (0.01 sec)

Records: 5  Duplicates: 0  Warnings: 0

 

mysql> select * from test1;

+----+------+

| id | name |

+----+------+

|  1 | tom1 |

|  2 | tom2 |

|  3 | tom3 |

|  4 | tom4 |

|  5 | tom5 |

+----+------+

5 rows in set (0.00 sec)

测试

下面就是测试的工作了,这里有个php脚本,用于测试memcache是否缓存数据成功
需要为这个脚本添加一个只读的数据库用户,命令格式

mysql> grant select on testdb1.* to [email protected]‘%‘ identified by ‘123456‘;

Query OK, 0 rows affected, 1 warning (0.00 sec)

web服务器上创建测试脚本内容如下:

[[email protected] html]# cat /usr/local/nginx1.10/html/test_db.php

<?php

$memcachehost = ‘192.168.31.250‘;

$memcacheport = 11211;

$memcachelife = 60;

$memcache = new Memcache;

$memcache->connect($memcachehost,$memcacheport) or die ("Could not connect");

$query="select * from test1 limit 10";

$key=md5($query);

if(!$memcache->get($key))

{

                $conn=mysql_connect("192.168.31.225","user","123456");

                mysql_select_db(testdb1);

                $result=mysql_query($query);

while ($row=mysql_fetch_assoc($result))

                {

                        $arr[]=$row;

                }

                $f = ‘mysql‘;

                $memcache->add($key,serialize($arr),0,30);

                $data = $arr ;

}

else{

        $f = ‘memcache‘;

        $data_mem=$memcache->get($key);

        $data = unserialize($data_mem);

}

echo $f;

echo "<br>";

echo "$key";

echo "<br>";

//print_r($data);

foreach($data as $a)

{

echo "number is <b><font color=#FF0000>$a[id]</font></b>";

echo "<br>";

echo "name is <b><font color=#FF0000>$a[name]</font></b>";

echo "<br>";

}

?>

访问页面测试

技术分享

如果出现mysql表示memcached中没有内容,需要memcached从数据库中取得

再刷新页面如果有memcache标志表示这次的数据是从memcached中取得的

memcached有个缓存时间默认是1分钟,过了一分钟后,memcached需要重新从数据库中取得数据

技术分享

查看 Memcached 缓存情况

我们需要使用 telnet 命令查看

[[email protected] ~]# telnet 192.168.31.250 11211

Trying 192.168.31.250...

Connected to 192.168.31.250.

Escape character is ‘^]‘.

stats

STAT pid 1681                    //Memcached 进程的ID

STAT uptime 8429                //进程运行时间

STAT time 1479142306             //当前时间

STAT version 1.4.33                // Memcached 版本

STAT libevent 2.0.22-stable

STAT pointer_size 64

STAT rusage_user 1.218430

STAT rusage_system 1.449512

STAT curr_connections 5

STAT total_connections 32

STAT connection_structures 10

STAT reserved_fds 20

STAT cmd_get 25//总共获取数据的次数(等于 get_hits + get_misses

STAT cmd_set 19 //总共设置数据的次数

STAT cmd_flush 4

STAT cmd_touch 0

STAT get_hits 15//命中了多少次数据,也就是从 Memcached 缓存中成功获取数据的次数

STAT get_misses 10//没有命中的次数

STAT get_expired 3

STAT get_flushed 1

STAT delete_misses 0

STAT delete_hits 0

STAT incr_misses 2

STAT incr_hits 2

STAT decr_misses 0

STAT decr_hits 0

STAT cas_misses 0

STAT cas_hits 0

STAT cas_badval 0

STAT touch_hits 0

STAT touch_misses 0

STAT auth_cmds 0

STAT auth_errors 0

STAT bytes_read 3370

STAT bytes_written 15710

STAT limit_maxbytes 2147483648//总的存储大小,默认为 64M

STAT accepting_conns 1

STAT listen_disabled_num 0

STAT time_in_listen_disabled_us 0

STAT threads 4

STAT conn_yields 0

STAT hash_power_level 16

STAT hash_bytes 524288

STAT hash_is_expanding 0

STAT malloc_fails 0

STAT log_worker_dropped 0

STAT log_worker_written 0

STAT log_watcher_skipped 0

STAT log_watcher_sent 0

STAT bytes 584//当前所用存储大小

STAT curr_items 3

STAT total_items 17

STAT expired_unfetched 2

STAT evicted_unfetched 0

STAT evictions 0

STAT reclaimed 4

STAT crawler_reclaimed 0

STAT crawler_items_checked 0

STAT lrutail_reflocked 0

END

命中率= get_hits/ cmd_get


本文出自 “duyuheng” 博客,谢绝转载!

以上是关于Linux之搭建memcache缓存服务器的主要内容,如果未能解决你的问题,请参考以下文章

Linux之搭建redis缓存服务器

NOSQL之Memcached缓存服务实战精讲第一部

memcache 搭建缓存服务器

memcached高缓存搭建

部署网站运行平台LNMP + Memcached缓存

部署LNMP动静分离并搭建memcache缓存服务器