【Linux基础服务教程】memcached缓存服务器
一、关于memcached
- 开源的
- 高性能的
- 分布式缓存服务器
- 基于内存存储数据、key-value

二、memcached内存分配方式

默认分配的内存大小为
48Bytes,以1.25倍向上递僧
三、安装memcached
A.安装libevent依赖
自行准备安装包
[root@localhost ~]# tar xf libevent-2.1.8-stable.tar.gz 
[root@localhost ~]# cd libevent-2.1.8-stable/
[root@localhost libevent-2.1.8-stable]# ./configure --prefix=/usr/local/libevent 
[root@localhost libevent-2.1.8-stable]# make && make install
B.安装memcached
[root@localhost ~]# wget https://www.memcached.org/files/memcached-1.6.19.tar.gz
[root@localhost ~]# tar xf memcached-1.6.19.tar.gz 
[root@localhost ~]# cd memcached-1.6.19/
[root@localhost memcached-1.6.19]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local/libevent 
[root@localhost memcached-1.6.19]# make && make install 
C.启动memcached
[root@localhost ~]# useradd -s /sbin/nologin memcached
[root@localhost ~]# /usr/local/memcached/bin/memcached -p 11211 -l 192.168.140.12 -u memcached -d -m 500M -c 2000 -n 20 -f 2 -t 10 
[root@localhost ~]# netstat -antp | grep memca
tcp        0      0 192.168.140.12:11211    0.0.0.0:*               LISTEN      25743/memcached     
[root@localhost ~]# ps -elf | grep memcached
1 S memcach+  25743      1  0  80   0 - 214343 ep_pol 15:53 ?       00:00:00 /usr/local/memcached/bin/memcached -p 11211 -l 192.168.140.12 -u memcached -d -m 500M -c 2000 -n 20 -f 2 -t 10
启动参数说明:
-p端口
-l监听地址
-u启动用户
-d后台启动
-m允许memcached所使用的最大内存
-c最大并发连接数
-f增长因子,默认1.25倍
-nmemcached分配内存的基本大小,默认48B
-t线程数
D.测试数据读写
[root@localhost ~]# telnet 192.168.140.12 11211
Trying 192.168.140.12...
Connected to 192.168.140.12.
Escape character is '^]'.
set name 0 20 6     20  过期时间  6 数据的长度
martin
STORED
get name
VALUE name 0 6
martin
END
get name
END
quit
E.利用PHP连接memcached
[root@localhost ~]# yum install -y httpd php gd php-gd php-devel php-pecl-memcache
[root@localhost ~]# php -m | grep -i mem
memcache
[root@localhost ~]# vim /var/www/html/test1.php
<?php
   $memcache_obj = memcache_connect('192.168.140.10', 11211);
   $memcache_obj->add("name", "Martin");
   echo $memcache_obj->get("name");
?>
四、关于分布式算法
1.根据hash值的余数
原理: “根据服务器台数的余数进行分散”。求得键的整数哈希值,再除以服务器台数,根据其余数来选择服务器。
缺点: 余数计算的方法简单,数据的hash也相当优秀,但也有其缺点。那就是当添加或移除服务器时,缓存重组的;代价相当巨大。添加服务器后余数就会产生巨变,这样就无法获取与保存时相同的服务器,从而影响缓存的命中率。
2.一致性hash算法
原理:
Consistent Hashing: 首先求出memcached服务器(节点)的哈希值,并将其配置到0~2^32的圆continuum上。然后用同样的方法求出存储数据的键的哈希值,并映射到圆上。然后从数据映射到的位置开始顺时针查找,将数据保存到找到的第一个服务器上。如果超过2^32仍然找不到服务器,就会保存到第一台memcached服务器上。

 
                     
                
             
                 
            
评论