memcache缓存应用(LNMP+memcache)

栏目: 数据库 · 发布时间: 6年前

内容简介:环境:软件:步骤

环境:

memcache:192.168.154.131
nginx:192.168.154.132
php:192.168.154.133
mysql:192.168.154.134

软件:

memcache上:libevent-2.0.22-stable.tar.gz、memcached-1.4.33.tar.gz
下载地址:http://libevent.org/ 
下载地址:http://memcached.org/downloads 
nginx上:nginx-1.14.0.tar.gz
下载地址:http://nginx.org/en/download.html 
php上:libmcrypt-2.5.7.tar.gz、php-5.6.27.tar.gz、memcache-3.0.8.tgz
下载地址:https://sourceforge.net/projects/mcrypt/files/Libmcrypt/2.5.8/ 
下载地址:http://php.net/downloads.php 
mysql上:mysql-8.0.11-linux-glibc2.12-x86_64.tar.gz(二进制包)
下载地址:https://dev.mysql.com/downloads/mysql/

步骤

nginx部分

groupadd -r www

useradd -r -g www -s /sbin/nologin www

tar zxf nginx-1.14.0.tar.gz

cd nginx-1.14.0

./configure --prefix=/usr/local/nginx \
--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

make && make install

ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin

nginx

firewall-cmd --permanent --add-port=80/tcp

firewall-cmd --reload

nginx配置文件/usr/local/nginx/conf/nginx.conf

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/nginx/nginx_tmp;
	fastcgi_intercept_errors on;
	fastcgi_cache_path /usr/local/nginx/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 localhost;
		#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 192.168.154.132;
				if ($invalid_referer) {
				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 192.168.154.133:9000;
			fastcgi_index index.php;
			include fastcgi.conf;
#关闭fastcgi的缓存			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 -s reload

php部分

tar zxf libmcrypt-2.5.7.tar.gz

cd libmcrypt-2.5.7

./configure --prefix=/usr/local/libmcrypt && make && make install

yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel

tar zxf php-5.6.27.tar.gz

cd php-5.6.27

./configure --prefix=/usr/local/php --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

make && make install

cp php.ini-production /etc/php.ini

cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm

cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf

chmod +x /etc/init.d/php-fpm

chkconfig --add php-fpm

chkconfig php-fpm on

sed -i 's#;pid = run/php-fpm.pid#pid = run/php-fpm.pid#g' /usr/local/php/etc/php-fpm.conf

sed -i 's/listen = 127.0.0.1:9000/listen = 0.0.0.0:9000/g' /usr/local/php/etc/php-fpm.conf

sed -i 's/pm.max_children = 5/pm.max_children = 300/g' /usr/local/php/etc/php-fpm.conf

sed -i 's/pm.start_servers = 2/pm.start_servers = 10/g' /usr/local/php/etc/php-fpm.conf

sed -i 's/pm.min_spare_servers = 1/pm.min_spare_servers = 10/g' /usr/local/php/etc/php-fpm.conf

sed -i 's/pm.max_spare_servers = 3/pm.max_spare_servers = 50/g' /usr/local/php/etc/php-fpm.conf

service php-fpm start

mysql部分

rpm -e --nodeps mariadb-libs

groupadd -r mysql 

useradd -r -g mysql -s /bin/false -M mysql
 
tar zxf mysql-8.0.11-linux-glibc2.12-x86_64.tar.gz

mv mysql-8.0.11-linux-glibc2.12-x86_64 /usr/local/mysql

mkdir /usr/local/mysql/data

chown -R mysql:mysql /usr/local/mysql/

ln -s /usr/local/mysql/bin/* /usr/local/bin

cat >> /etc/my.cnf << EOF
[client]
socket=/usr/local/mysql/data/mysql.sock
[mysqld]
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
port=3306
pid-file=/usr/local/mysql/data/mysql.pid
server_id=1
socket=/usr/local/mysql/data/mysql.sock
log-error=/usr/local/mysql/data/mysql.err
EOF

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

cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld

chkconfig --add mysqld

chkconfig on mysqld

systemctl daemon-reload

systemctl start mysqld

memcache部分

tar zxf libevent-2.0.22-stable.tar.gz

cd libevent-2.0.22-stable/

./configure && make&& make install

tar zxf memcached-1.4.33.tar.gz 

cd memcached-1.4.33/

./configure --prefix=/usr/local/memcached --with-libevent=/usr/local

make && make install

vi ~/.bash_profile

MEMCACHED_HOME=/usr/local/memcached
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MEMCACHED_HOME/lib
memcached -d -m 2048 -l 192.168.154.131 -p 11211 -u root -c 10240 -P /usr/local/memcached/memcached.pid

firewall-cmd --permanent --add-port=11211/tcp

firewall-cmd --reload

php

加载memcache.so(使php作为memcache的客户端)

tar zxf memcache-3.0.8.tgz 

cd memcache-3.0.8/

/usr/local/php/bin/phpize

./configure --enable-memcache --with-php-config=/usr/local/php/bin/php-config

make && make install

注意:安装完后会有类似这样的提示: Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-zts-20131226/;记住这个路径,需要加载到php的配置文件中。

vim /etc/php.ini

##查找extension并在对应位置添加
extension=/usr/local/php/lib/php/extensions/no-debug-zts-20131226/memcache.so
##在末尾添加
session.save_handler = memcache
session.save_path = "tcp://192.168.154.131:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
service php-fpm restart

在nginx上

编写php测试页面。vim /usr/local/nginx/html/index.php

<?php
phpinfo();
?>

访问 http://192.168.154.132 ,应当可以看到memcache和session字样。

(成功表示php上安装好了memcache.so)

编写memcache测试页面。vim /usr/local/nginx/html/test.php

<?php
$memcache = new Memcache;
$memcache->connect('192.168.154.131', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."
";
$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)
";
$get_result = $memcache->get('key');
echo "Data from the cache:
";
var_dump($get_result);
?>

预计会输出四行字符,有memcache版本信息等

(成功表示连接到了memcache服务器)

编写测试memcache的session共享脚本,vim /usr/local/nginx/html/session.php

<?php
session_start();
if (!isset($_SESSION['session_time']))
{
  $_SESSION['session_time'] = time();
}
echo "now_time:".time()."
"; 
echo "session_id:".session_id()."
";
?>

预计输出session_time、now_time、session_id

使用telnet连接memcache

telnet 192.168.154.131 11211

然后get session_id的值,如果得到的session_time和网页上的一样表示session共享成功。

mysql

mysql> create database testdb1;

mysql> use testdb1;

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;

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

mysql> select * from test1;
+----+------+
| id | name |
+----+------+
| 1 | tom1 |
| 2 | tom2 |
| 3 | tom3 |
| 4 | tom4 |
| 5 | tom5 |
+----+------+
5 rows in set (0.00 sec)

mysql> grant select on testdb1.* to user@'%' identified by '123456';

在nginx上

编辑memcache缓存mysql测试页面,vim /usr/local/nginx/html/test_db.php

<?php
$memcachehost = '192.168.154.131';
$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.154.134","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>";
}
?>

预计会输出memcache的key,和我们在mysql创建的数据表的数据

(成功即表示memcache缓存到mysql的数据)


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

程序员代码面试指南:IT名企算法与数据结构题目最优解

程序员代码面试指南:IT名企算法与数据结构题目最优解

左程云 / 电子工业出版社 / 2015-9 / 79.00元

这是一本程序员面试宝典!书中对IT名企代码面试各类题目的最优解进行了总结,并提供了相关代码实现。针对当前程序员面试缺乏权威题目汇总这一痛点,本书选取将近200道真实出现过的经典代码面试题,帮助广大程序员的面试准备做到万无一失。“刷”完本书后,你就是“题王”!__eol__本书采用题目+解答的方式组织内容,并把面试题类型相近或者解法相近的题目尽量放在一起,读者在学习本书时很容易看出面试题解法之间的联......一起来看看 《程序员代码面试指南:IT名企算法与数据结构题目最优解》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具