码迷,mamicode.com
首页 > 系统相关 > 详细

Memcached在企业中的应用

时间:2018-08-25 11:42:46      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:couchbase   cli   byte   install   带宽   tween   集群架构   mon   目录   

Memcached简介

Memcached是一个自由开源的,高性能,分布式内存对象缓存系统。

Memcached是以LiveJournal旗下Danga Interactive公司的Brad Fitzpatric为首开发的一款软件。现在已成为mixi、hatena、Facebook、Vox、LiveJournal等众多服务中提高Web应用扩展性的重要因素。

Memcached是一种基于内存的key-value存储,用来存储小块的任意数据(字符串、对象)。这些数据可以是数据库调用、API调用或者是页面渲染的结果。

Memcached简洁而强大。它的简洁设计便于快速开发,减轻开发难度,解决了大数据量缓存的很多问题。它的API兼容大部分流行的开发语言。

本质上,它是一个简洁的key-value存储系统。

一般的使用目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度、提高可扩展性。

技术分享图片

特征

memcached作为高速运行的分布式缓存服务器,具有以下的特点。

  • 协议简单
  • 基于libevent的事件处理
  • 内置内存存储方式
  • memcached不互相通信的分布式

Memcached在企业中架构应用的位置

第一个作为数据库的内容缓存
第二个作为集群节点会话共享
那么架构上讲可以分为三层前端用户层 中间应用程序层,后面就是数据存储层,那么当数据通过互联网到达机房之后会先找负载均衡器,负载均衡器请求web服务器,假如是浏览一篇博文,那么web服务器先找内存缓存,如果内存缓存没有,那么会把请求转发到数据库,从数据库读完之后,再把数据放到内存一份,第二个用户再访问的时候就先访问缓存,就不会找数据库了,那么数据库的压力就降下来了,这就是内存缓存的作用。
CDN服务 ,就是一个分布式缓存系统,当用户请求图片的时候会先找CDN,CDN有就直接给用户访问了,大幅度的减轻网站压力,同时节省带宽。
缓存带来的问题:
客户发一张帖子到数据库里边也缓存到缓存memcached里边,别人访问就访问缓存了,发帖子的人发现我这个内容需要修改下,是先更新数据库,
不是先改缓存,其它用户访问就访问到缓存了,还是老的数据,有一个数据一致性的问题,所以程序员们这样设计,它在更新数据库的时候,它同时发送一个请求告诉memcached,对应的帖子过期了,那么memcached会把过期的数据删除,,会有这么一个机制,那么对于前端包括CDN,我们在更新图片的时候,告诉CND把旧的删除,但是对于图片来讲很少有更改的操作,它的更改是更改文件名操作上传,对于CDN来讲是不同的数据。


session保持不管是nginx还是apache只要用php,默认情况下会放在/tmp目录下,是在php.ini中指定的。
对于不同的服务器来讲,每个web服务器都放在自己的tmp下,早期会把会话保持到tmpfs文件系统里。
那么在php.ini里边可以用IP加端口指定会话保持

在企业工作当中memcached缓存重启数据全丢,假如数据丢了,数据库压力暴大
假如缓存每秒8000并发,数据库并发1000,一下压到数据库,数据库压力大就会down机,数据库刚要启又down
这种情况叫雪崩效应,这种情况下通常把负载均衡下的web用防火墙禁止对外访问。或者停掉
之后把memcached开启来,通过程序初始化把memcached缓存好,然后慢慢的把web打开。

lvs或者haproxy 做cache的负载均衡
假设缓存把数据a.jpg存储在cache1上,当用户访问a.JPG,如果访问
到cache2上去了,那cache2上没有就找数据库了,那数据库压力不就大嘛,
那缓存有没有了,有,只不过在cache1上,如果缓存把数据b.jpg存储在cache2上
那用户访问被请求到cache1上,那cache1上没有,那也只能找数据库,那这就是一个问题
那在前边负载算法就要指定url算法或者hash了,只要是这张图片只要是这个路径就存储到指定地点。
web集群是每个服务器内容一样的,不一样的放在后端NFS里边了 ,所以web集群可以wrr算法。

memcached应用部署

[root@TCS tools]# cat /etc/redhat-release 
CentOS release 6.5 (Final) #操作系统

1. memcached服务端安装
tar xf libevent-1.4.13-stable.tar.gz 
cd libevent-1.4.13-stable
./configure
make
make install

tar xf memcached-1.4.13.tar.gz 
cd memcached-1.4.13
./configure
make
make install
cd ..
[root@TCS tools]# echo "/usr/local/lib" >> /etc/ld.so.conf #配置ld.so.conf路径防止启动出错,5.8系统环境可以忽略
[root@TCS tools]# ldconfig 

[root@TCS tools]# which memcached
/usr/local/bin/memcached
[root@TCS tools]# /usr/local/bin/memcached -h   #memcached相关参数
memcached 1.4.13
-p <num>      TCP port number to listen on (default: 11211)
-U <num>      UDP port number to listen on (default: 11211, 0 is off)
-s <file>     UNIX socket path to listen on (disables network support)
-a <mask>     access mask for UNIX socket, in octal (default: 0700)
-l <addr>     interface to listen on (default: INADDR_ANY, all addresses)
              <addr> may be specified as host:port. If you dont specify
              a port number, the value you specified with -p or -U is
              used. You may specify multiple addresses separated by comma
              or by using -l multiple times
-d            run as a daemon
-r            maximize core file limit
-u <username> assume identity of <username> (only when run as root)
-m <num>      max memory to use for items in megabytes (default: 64 MB)
-M            return error on memory exhausted (rather than removing items)
-c <num>      max simultaneous connections (default: 1024)
-k            lock down all paged memory.  Note that there is a
              limit on how much memory you may lock.  Trying to
              allocate more than that would fail, so be sure you
              set the limit correctly for the user you started
              the daemon with (not for -u <username> user;
              under sh this is done with ulimit -S -l NUM_KB).
-v            verbose (print errors/warnings while in event loop)
-vv           very verbose (also print client commands/reponses)
-vvv          extremely verbose (also print internal state transitions)
-h            print this help and exit
-i            print memcached and libevent license
-P <file>     save PID in <file>, only used with -d option
-f <factor>   chunk size growth factor (default: 1.25)
-n <bytes>    minimum space allocated for key+value+flags (default: 48)
-L            Try to use large memory pages (if available). Increasing
              the memory page size could reduce the number of TLB misses
              and improve the performance. In order to get large pages
              from the OS, memcached will allocate the total item-cache
              in one large chunk.
-D <char>     Use <char> as the delimiter between key prefixes and IDs.
              This is used for per-prefix stats reporting. The default is
              ":" (colon). If this option is specified, stats collection
              is turned on automatically; if not, then it may be turned on
              by sending the "stats detail on" command to the server.
-t <num>      number of threads to use (default: 4)
-R            Maximum number of requests per event, limits the number of
              requests process for a given connection to prevent 
              starvation (default: 20)
-C            Disable use of CAS
-b            Set the backlog queue limit (default: 1024)
-B            Binding protocol - one of ascii, binary, or auto (default)
-I            Override the size of each slab page. Adjusts max item size
              (default: 1mb, min: 1k, max: 128m)
-o            Comma separated list of extended or experimental options
              - (EXPERIMENTAL) maxconns_fast: immediately close new
                connections if over maxconns limit
              - hashpower: An integer multiplier for how large the hash
                table should be. Can be grown at runtime if not big enough.
                Set this based on "STAT hash_power_level" before a 
                restart.
2.memcached启动
[root@TCS tools]# memcached -p 11211 -u root -m 16m -c 10240 -d     # -p指定端口,-u 用户,-m 内存大小,-c 最大并发连接数,-d 后台运行
#其它参数:
-P  设置保持Memcache的pid文件   -vv 以very vrebose模式启动,调试信息和错误输出到控制台
[root@TCS tools]# lsof -i :11211
COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
memcached 13875 root   26u  IPv4  20953      0t0  TCP *:memcache (LISTEN)
memcached 13875 root   27u  IPv6  20954      0t0  TCP *:memcache (LISTEN)
memcached 13875 root   28u  IPv4  20957      0t0  UDP *:memcache 
memcached 13875 root   29u  IPv6  20958      0t0  UDP *:memcache 

#memcached的多实例
[root@TCS tools]# memcached -p 11212 -u root -m 16m -c 10240 -d
[root@TCS tools]# netstat -lnt|grep 1121
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN      
tcp        0      0 0.0.0.0:11212               0.0.0.0:*                   LISTEN      
tcp        0      0 :::11211                    :::*                        LISTEN      
tcp        0      0 :::11212                    :::*                        LISTEN 

3. 开机自启动
放到/etc/rc.local中
memcached -p 11212 -u root -m 16m -c 10240 -d

4.写入数据检查结果
a.通过nc写入
[root@TCS tools]# printf "set key008 0 0 10\r\noldboy0987\r\n"|nc 127.0.0.1 11211  #增加 ,命令的字节是10,后面就要10个字符,否则添加不成功。
STORED  
[root@TCS tools]# printf "get key008\r\n"|nc 127.0.0.1 11211   #查询
VALUE key008 0 10
oldboy0987
END
[root@TCS tools]# printf "delete key008\r\n"|nc 127.0.0.1 11211   #删除
DELETED
[root@TCS tools]# printf "get key008\r\n"|nc 127.0.0.1 11211   #查询
END

b.通过telnet写数据
[root@TCS tools]# telnet 192.168.179.134 11211
Trying 192.168.179.134...
Connected to 192.168.179.134.
Escape character is ^].
set key 0 0 10  #写数据
zhousq
STORED
get key   #查询
VALUE key 0 10
zhousq
END

delete key  #删除
DELETED

get key
END         #CTRL+] 退回,然后qujit退出      #建议用第一种,有时telnet会很慢

通过stats可以查看写入数据的状态信息
[root@TCS tools]# printf "stats\r\n"|nc 127.0.0.1 11211
STAT pid 14254
STAT uptime 312
STAT time 1461179190
STAT version 1.4.13
STAT libevent 1.4.13-stable
STAT pointer_size 64
STAT rusage_user 0.000000
STAT rusage_system 0.015997
STAT curr_connections 10
STAT total_connections 14
STAT connection_structures 11
STAT reserved_fds 20
STAT cmd_get 1
STAT cmd_set 0
STAT cmd_flush 0
STAT cmd_touch 0
STAT get_hits 0   #查询 命中的数量
STAT get_misses 1   #丢失数量
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 0
STAT incr_hits 0
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 31
STAT bytes_written 1039
STAT limit_maxbytes 16777216    #内存大小
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT bytes 0
STAT curr_items 0       #往数据库插一条数据就有一条记录
STAT total_items 0       #当前没有记录,因为删除了
STAT evictions 0
STAT reclaimed 0
END


5. 重启数据丢失
(通过简单shell可以让memcache变为持久化存储) [root@TCS tools]
# printf "get key\r\n"|nc 127.0.0.1 11211 #先查看数据 VALUE key 0 10 oldboy0987 END [root@TCS tools]# ps -ef |grep memcached root 13875 1 0 Apr20 ? 00:00:00 memcached -p 11211 -u root -m 16m -c 10240 -d root 13883 1 0 Apr20 ? 00:00:00 memcached -p 11212 -u root -m 16m -c 10240 -d root 14237 14109 0 03:00 pts/2 00:00:00 grep memcached [root@TCS tools]# kill 13875 #kill掉memcached [root@TCS tools]# ps -ef |grep memcached root 13883 1 0 Apr20 ? 00:00:00 memcached -p 11212 -u root -m 16m -c 10240 -d root 14239 14109 0 03:00 pts/2 00:00:00 grep memcached [root@TCS tools]# [root@TCS tools]# memcached -p 11211 -u root -m 16m -c 10240 -d #重启 [root@TCS tools]# printf "get key\r\n"|nc 127.0.0.1 11211 #重新查看 END 6. memcache客户端安装 tar xf memcache-2.2.5.tgz cd memcache-2.2.5 /application/php/bin/phpize ./configure --with-php-config=/application/php/bin/php-config make make install ls /application/php5.3.27/lib/php/extensions/no-debug-zts-20090626/ 7. 测试 [root@TCS www]# cat test.php <?php $mem = new Memcache; $mem->connect("192.168.179.134", 11211) or die("Could not connect"); $version = $mem->getVersion(); echo "Server‘s version: ".$version."<br/>\n"; $mem->set(testkey, Hello World, 0, 600) or die("Failed to save data at the memcached server"); echo "Store data in the cache (data will expire in 600 seconds)<br/>\n"; $get_result = $mem->get(testkey); echo "$get_result is from memcached server."; ?> #浏览器访问 http://192.168.179.134/test.php 返回结果如下。说明已经测试OK Servers version: 1.4.13 Store data in the cache (data will expire in 600 seconds) Hello World is from memcached server. 8.session共享会话存储.在php.ini文件中改为相对应选项 session.save_handler memcache session.save_path tcp://192.168.179.134:11211 把所有web服务器的php.ini改成一样的地址,这样就保持了会话保持 集群架构多服务器同步session的多种方式: 1.lb层可以做会话保持:例如: lvs -p nginx ip_hash hapoxy cookie insert PHP JAVA都可以用 2.软件层,可以做session复制,例如: tomcat ,resin,couchbase 3,session共享,例如: memcached或者其它工具的nosql工具,php常用这个。 4.高并发场景:例如门户网站用cookies或cookies配合session把用户级会话信息缓存在用户本地; 9.memcache 图形管理工具 [root@TCS tools]# tar xf memadmin-1.0.12.tar.gz [root@TCS tools]# mv memadmin /var/html/www/ [root@TCS tools]# /application/apache/bin/apachectl graceful http://192.168.179.134/memadmin/ 默认用户密码 admin:admin 10.内存管理机制的调优
指定1.25组间差距比因子为2时小得多,更适合缓存几百字节的记录。 [root@TCS tools]
# memcached -m 512m -d -u root -c 8192 -f 2 -vv [root@TCS tools]# slab class 1: chunk size 96 perslab 10922 slab class 2: chunk size 192 perslab 5461 slab class 3: chunk size 384 perslab 2730 slab class 4: chunk size 768 perslab 1365 slab class 5: chunk size 1536 perslab 682 slab class 6: chunk size 3072 perslab 341 slab class 7: chunk size 6144 perslab 170 [root@TCS tools]# memcached -m 512m -d -u root -c 8192 -f 1.25 -vv [root@TCS tools]# slab class 1: chunk size 96 perslab 10922 slab class 2: chunk size 120 perslab 8738 slab class 3: chunk size 152 perslab 6898 slab class 4: chunk size 192 perslab 5461 slab class 5: chunk size 240 perslab 4369 slab class 6: chunk size 304 perslab 3449 11.memcachedb和TTSERVER持久化存储,兼容memcached协议。 12.memcached监控 check_me_sh #!/bin/sh [ $# -ne 2 ]&&{ echo "$0 ip port" exit } export oldboy=key export wwwServerIp=$1 export wwwServerPort=$2 cmd="nc $wwwServerIp $wwwServerPort" printf "delete $oldboy\r\n" | $cmd >/dev/null 2>&1 sleep 1 printf "set $oldboy 0 0 6\r\noldboy\r\n"|$cmd >/dev/null 2>&1 if [ `printf "get $oldboy\r\n"|$cmd|grep oldboy|wc -l` -eq 1 ] then echo "mc is alive." exit 0 else echo "mc is dead." exit 2 fi

 

Memcached在企业中的应用

标签:couchbase   cli   byte   install   带宽   tween   集群架构   mon   目录   

原文地址:https://www.cnblogs.com/w787815/p/9532659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!