21.1 nosql介绍
什么是 NoSQL?
非关系型数据库就是 NoSQL,关系型数据库代表 MySQL
对于关系型数据库来说,是需要把数据存储到库、表、行、字段里,查询的时候根据条件一行一行地去匹配,当量非常大的时候就很耗费时间和资源,尤其是数据是需要从磁盘里去检索
NoSQL 数据库存储原理非常简单(典型的数据类型为 k-v ),不存在繁杂的关系链,比如mysql查询的时候,需要找到对应的库、表(通常是多个表)以及字段。
NoSQL 数据可以存储在内存里,查询速度非常快
NoSQL 在性能表现上虽然能优于关系型数据库,但是它并不能完全替代关系型数据库
NoSQL 因为没有复杂的数据结构,扩展非常容易,支持分布式
常见的 NoSQL 数据库:
k-v 形式的:memcached、redis 适合储存用户信息,比如会话、配置文件、参数、购物车等等。这些信息一般都和ID(键)挂钩,这种情景下键值数据库是个很好的选择。
文档数据库:mongodb 将数据以文档的形式储存。每个文档都是一系列数据项的集合。每个数据项都有一个名称与对应的值,值既可以是简单的数据类型,如字符串、数字和日期等;也可以是复杂的类型,如有序列表和关联对象。数据存储的最小单位是文档,同一个表中存储的文档属性可以是不同的,数据可以使用 XML、JSON 或者 JSONB 等多种形式存储。
列存储 Hbase
图 Neo4J、Infinite Graph、OrientDB
21.2 memrcached介绍
Memcached 是国外社区网站 LiveJournal 团队开发,目的是为了通过缓存数据库查询结果,减少数据库访问次数,从而提高动态web站点性能。
官方站点 http://www.memcached.org/
数据结构简单(k-v),数据存放在内存里
多线程
基于 c/s 架构,协议简单
基于 libevent 的事件处理
自主内存存储处理(slab allowcation)
数据过期方式:Lazy Expiration 和 LRU
Memcached 的数据流向:
Slab allocation:
Slab Allocation 的原理:
将分配的内存分割成各种尺寸的块(chunk), 并把尺寸相同的块分成组(chunk的集合),每个chunk集合被称为slab。
Memcached 的内存分配以 Page 为单位,Page 默认值为1M,可以在启动时通过 -I 参数来指定。
Slab是由多个 Page 组成的,Page 按照指定大小切割成多个 chunk。
Growth factor:
Memcached 在启动时通过 -f 选项可以指定 Growth Factor 因子。该值控制 chunk 大小的差异。默认值为1.25。
通过 memcached-tool 命令查看指定 Memcached 实例的不同 slab 状态,可以看到各 Item所占大小(chunk大小)差距为1.25
命令:# memcached-tool 127.0.0.1:11211 display
Memcached 的数据过期方式:
Lazy Expiration:
Memcached 内部不会监视记录是否过期,而是在 get 时查看记录的时间戳,检查记录是否过期。这种技术被称为 lazy(惰性)expiration。因此,Memcached 不会在过期监视上耗费 CPU 时间。
LRU:
Memcached 会优先使用已超时的记录的空间,但即使如此,也会发生追加新记录时空间不足的情况,此时就要使用名为 Least Recently Used(LRU)机制来分配空间。顾名思义,这是删除“最近最少使用”的记录的机制。因此,当内存空间不足时(无法从 slab class 获取到新的空间时),就从最近未被使用的记录中搜索,并将其空间分配给新的记录。从缓存的实用角度来看,该模型十分理想。
21.3 安装memcached
1、安装:yum install -y memcached
2、启动:systemctl start memcached
3、查看进程及端口:
[root@arslinux-01 ~]# ps aux|grep memcached memcach+ 8981 0.0 0.1 344092 1680 ? Ssl 21:07 0:00 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 1024 root 9003 0.0 0.0 112724 984 pts/0 R+ 21:07 0:00 grep --color=auto memcached [root@arslinux-01 ~]# netstat -lntp|grep memcached tcp 0 0 0.0.0.0:11211 0.0.0.0:* LISTEN 8981/memcached tcp6 0 0 :::11211 :::* LISTEN 8981/memcached /usr/bin/memcaced:
-u 指定运行 memcached 服务的用户
-p 指定监听端口
-m 指定 memcached分配内存(单位M)
-c 指定最大并发数
如何改参数?
1、用命令行启动,在启动时更改参数
2、更改 /etc/sysconfig/memcached 参数
[root@arslinux-01 ~]# cat /etc/sysconfig/memcached PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="64" OPTIONS=""
比如加上监听的ip,可以把OPTIONS="" 改为OPTIONS="127.0.0.1"
21.4 查看memcached状态
1、memcached -tool 工具
[root@arslinux-01 ~]# memcached-tool 127.0.0.1:11211 stats #127.0.0.1:11211 Field Value accepting_conns 1 auth_cmds 0 auth_errors 0 bytes 0 bytes_read 7 bytes_written 0 cas_badval 0 cas_hits 0 cas_misses 0 cmd_flush 0 cmd_get 0 cmd_set 0 cmd_touch 0 conn_yields 0 connection_structures 11 curr_connections 10 curr_items 0 decr_hits 0 decr_misses 0 delete_hits 0 delete_misses 0 evicted_unfetched 0 evictions 0 expired_unfetched 0 get_hits 0 get_misses 0 hash_bytes 524288 hash_is_expanding 0 hash_power_level 16 incr_hits 0 incr_misses 0 libevent 2.0.21-stable limit_maxbytes 67108864 listen_disabled_num 0 pid 8981 pointer_size 64 reclaimed 0 reserved_fds 20 rusage_system 0.065852 rusage_user 0.025768 threads 4 time 1562851027 total_connections 11 total_items 0 touch_hits 0 touch_misses 0 uptime 605 version 1.4.15
平时关注 get_hits ÷ curr_items 的值
2、nc 命令
1)安装 nc 命令
[root@arslinux-01 ~]# yum install -y nc
2)使用方法
[root@arslinux-01 ~]# echo stats |nc 127.0.0.1 11211 STAT pid 8981 STAT uptime 1325 STAT time 1562851747 STAT version 1.4.15 STAT libevent 2.0.21-stable STAT pointer_size 64 STAT rusage_user 0.050529 STAT rusage_system 0.097691 STAT curr_connections 10 STAT total_connections 12 STAT connection_structures 11 STAT reserved_fds 20 STAT cmd_get 0 STAT cmd_set 0 STAT cmd_flush 0 STAT cmd_touch 0 STAT get_hits 0 STAT get_misses 0 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 13 STAT bytes_written 1024 STAT limit_maxbytes 67108864 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 bytes 0 STAT curr_items 0 STAT total_items 0 STAT expired_unfetched 0 STAT evicted_unfetched 0 STAT evictions 0 STAT reclaimed 0 END
3、memstat 命令
1)安装 libmemcached
[root@arslinux-01 ~]# yum install -y libmemcached
2)使用方法
[root@arslinux-01 ~]# memstat --servers 127.0.0.1:11211 Server: 127.0.0.1 (11211) pid: 8981 uptime: 1625 time: 1562852047 version: 1.4.15 libevent: 2.0.21-stable pointer_size: 64 rusage_user: 0.058228 rusage_system: 0.119882 curr_connections: 10 total_connections: 13 connection_structures: 11 reserved_fds: 20 cmd_get: 0 cmd_set: 0 cmd_flush: 0 cmd_touch: 0 get_hits: 0 get_misses: 0 delete_misses: 0 delete_hits: 0 incr_misses: 0 incr_hits: 0 decr_misses: 0 decr_hits: 0 cas_misses: 0 cas_hits: 0 cas_badval: 0 touch_hits: 0 touch_misses: 0 auth_cmds: 0 auth_errors: 0 bytes_read: 30 bytes_written: 2069 limit_maxbytes: 67108864 accepting_conns: 1 listen_disabled_num: 0 threads: 4 conn_yields: 0 hash_power_level: 16 hash_bytes: 524288 hash_is_expanding: 0 bytes: 0 curr_items: 0 total_items: 0 expired_unfetched: 0 evicted_unfetched: 0 evictions: 0 reclaimed: 0
总结:
可以查看 Memcached 状态的方法:
1、memcached-tool 127.0.0.1:11211 stats
2、echo stats | nc 127.0.0.1 11211
3、memstat --servers 127.0.0.1:11211
21.5 memcached命令行
[root@arslinux-01 ~]# telnet 127.0.0.1 11211 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. set key2 0 30 2 12 STORED set key1 0 20 3 abc STORED get key1 VALUE key1 0 3 abc END get key2 END
set key名 过期时间 value的值
Memcached 语法规则:
\r\n \r\n
注:\r\n在windows下是Enter键
可以是set, add, replace
set 表示按照相应的
add 表示按照相应的
replace 表示按照相应的
客户端需要保存数据的key 是一个16位的无符号的整数(以十进制的方式表示)。该标志将和需要存储的数据一起存储,并在客户端get数据时返回。客户端可以将此标志用做特殊用途,此标志对服务器来说是不透明的。 为过期的时间。若为0表示存储的数据永远不过期(但可被服务器算法:LRU 等替换)。如果非0(unix时间或者距离此时的秒数),当过期后,服务器可以保证用户得不到该数据(以服务器时间为标准)。 需要存储的字节数,当用户希望存储空数据时 可以为0 需要存储的内容,输入完成后,最后客户端需要加上\r\n(直接点击Enter)作为结束标志。
Memcached数据示例:
set key3 1 100 4
1234
STORED
get key3
VALUE key3 1 4
1234
END
replace key3 1 0 5
abcde
STORED
get key3
VALUE key3 1 5
abcde
END
delete key3
DELETED
get key3
END
21.6 memcached数据导出和导入
memcached 重启之前最好数据导出,待重启后再导入
导出:
[root@arslinux-01 ~]# memcached-tool 127.0.0.1:11211 dump > data.txt Dumping memcache contents Number of buckets: 1 Number of items : 3 Dumping bucket 1 - 3 total items
导入:
[root@arslinux-01 ~]# nc 127.0.0.1 11211 < data.txt NOT_STORED NOT_STORED NOT_STORED
之所以显示 NOT_STORED,是因为之前数据时 add 添加的,数据导入无法覆盖
因此可以重启 memcached ,清空数据后再导入
[root@arslinux-01 ~]# systemctl restart memcached [root@arslinux-01 ~]# nc 127.0.0.1 11211 < data.txt STORED STORED STORED
不过实际上,数据并没有导入 memcached
因为 data.txt 里的时间戳已经过期
[root@arslinux-01 ~]# cat data.txt add k1 1 1562850422 5 12345 add name 1 1562850422 6 amings add age 1 1562850422 2 20 [root@arslinux-01 ~]# date -d @1562850422 2019年 07月 11日 星期四 21:07:02 CST [root@arslinux-01 ~]# date 2019年 07月 11日 星期四 22:23:49 CST
那么需要更改 data.txt 中的时间戳,之后再重新导入
[root@arslinux-01 ~]# date -d "+1 hour" +%s 1562858838 [root@arslinux-01 ~]# vim data.txt add k1 1 1562858838 5 12345 add name 1 1562858838 6 amings add age 1 1562858838 2 20
[root@arslinux-01 ~]# systemctl restart memcached [root@arslinux-01 ~]# nc 127.0.0.1 11211 < data.txt STORED STORED STORED
[root@arslinux-01 ~]# telnet 127.0.0.1 11211 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. get k1 VALUE k1 1 5 12345 END get name VALUE name 1 6 amings END get age VALUE age 1 2 20 END
21.7 php 连接 memcached
1、先安装 php 的 memcached 扩展
[root@arslinux-01 ~]# cd /usr/local/src/ [root@arslinux-01 src]# wget http://www.apelearn.com/bbs/data/attachment/forum/memcache-2.2.3.tgz [root@arslinux-01 src]# tar xvf memcache-2.2.3.tgz package.xml memcache-2.2.3/config.m4 memcache-2.2.3/config9.m4 memcache-2.2.3/config.w32 memcache-2.2.3/CREDITS memcache-2.2.3/example.php memcache-2.2.3/memcache.c memcache-2.2.3/memcache_queue.c memcache-2.2.3/memcache_session.c memcache-2.2.3/memcache_standard_hash.c memcache-2.2.3/memcache_consistent_hash.c memcache-2.2.3/memcache.dsp memcache-2.2.3/php_memcache.h memcache-2.2.3/memcache_queue.h memcache-2.2.3/README [root@arslinux-01 src]# cd memcache-2.2.3/
[root@arslinux-01 memcache-2.2.3]# /usr/local/php-fpm/bin/phpize //生成 config 文件 Configuring for: PHP Api Version: 20131106 Zend Module Api No: 20131226 Zend Extension Api No: 220131226 Cannot find autoconf. Please check your autoconf installation and the $PHP_AUTOCONF environment variable. Then, rerun this script.
出现以上错误,需要安装 autoconf ,可以 yum 安装
[root@arslinux-01 memcache-2.2.3]# yum install -y autoconf [root@arslinux-01 memcache-2.2.3]# /usr/local/php-fpm/bin/phpize Configuring for: PHP Api Version: 20131106 Zend Module Api No: 20131226 Zend Extension Api No: 220131226
[root@arslinux-01 memcache-2.2.3]# ./configure --with-php-config=/usr/local/php-fpm/bin/php-config [root@arslinux-01 memcache-2.2.3]# make && make install
完成安装后,最后会有以下提示,说明模块安装的位置
Installing shared extensions: /usr/local/php-fpm/lib/php/extensions/no-debug-non-zts-20131226/ [root@arslinux-01 memcache-2.2.3]# ls /usr/local/php-fpm/lib/php/extensions/no-debug-non-zts-20131226/ memcache.so opcache.a opcache.so
已生成 memcached.so 模块
2、编辑 php.ini 文件,添加 extension=php_memcached.dll
[root@arslinux-01 memcache-2.2.3]# vim /usr/local/php-fpm/etc/php.ini extension=memcache.so
3、查看 php-fpm 模块是否存在
[root@arslinux-01 memcache-2.2.3]# /usr/local/php-fpm/bin/php -m|grep memcache memcache
4、测试
[root@arslinux-01 ~]# curl www.apelearn.com/study_v2/.memcache.txt > 1.php 2>/dev/null
[root@arslinux-01 ~]# cat 1.php connect("localhost", 11211); //保存数据 $mem->set('key1', 'This is first value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val ."
"; //替换数据 $mem->replace('key1', 'This is replace value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "
"; //保存数组数据 $arr = array('aaa', 'bbb', 'ccc', 'ddd'); $mem->set('key2', $arr, 0, 60); $val2 = $mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "
"; //删除数据 $mem->delete('key1'); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "
"; //清除所有数据 $mem->flush(); $val2 = $mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "
"; //关闭连接 $mem->close(); ?>
[root@arslinux-01 ~]# /usr/local/php-fpm/bin/php 1.php Get key1 value: This is first value
Get key1 value: This is replace value
Get key2 value: Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd )
Get key1 value:
Get key2 value:
[root@arslinux-01 ~]#
或者将1.php放到某个虚拟主机根目录下面,在浏览器访问,即可看到效果
最终可以看到数据如下就是成功了
21.8 memcached 中存储 sessions
1、下载 php 测试文件
[root@arslinux-01 ~]# wget http://study.lishiming.net/.mem_se.txt
[root@arslinux-01 ~]# cat .mem_se.txt
"; print $_SESSION['TEST3']; print "
"; print session_id(); ?>
2、查看 nginx 默认虚拟主机的文件夹
[root@arslinux-01 ~]# cat /usr/local/nginx/conf/vhost/ aaa.com.conf load.conf proxy.conf ssl.conf test.com.conf
[root@arslinux-01 ~]# cat /usr/local/nginx/conf/vhost/aaa.com.conf server { listen 80 default_server; server_name aaa.com; index index.html index.htm index.php; root /data/wwwroot/default; location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/tmp/arslinux.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /data/wwwroot/default.com$fastcgi_script_name; } }
3、将.mem_se.txt 拷到 /data/wwwroot/default 下
[root@arslinux-01 ~]# cd /data/wwwroot/default/ [root@arslinux-01 default]# cp /root/.mem_se.txt 1.php [root@arslinux-01 default]# ls 1.php index.html [root@arslinux-01 default]# curl localhost/1.php File not found.
★★★查看了默认虚拟服务器配置文件,看到/data/wwwroot/default.com$fastcgi_script_name,因此目录文件名臣不对,更改名称后,正常
[root@arslinux-01 wwwroot]# mv default/ default.com/ [root@arslinux-01 wwwroot]# curl localhost/1.php 1562859350
1562859350
hldn2qa8n3kmel8tiieckqoj17 [root@arslinux-01 wwwroot]# ll /tmp/ |grep sess -rw------- 1 php-fpm php-fpm 37 7月 11 23:35 sess_hldn2qa8n3kmel8tiieckqoj17 [root@arslinux-01 wwwroot]# curl localhost/1.php 1562859435
1562859435
593f6g4rk451qq0310840boqc0 [root@arslinux-01 wwwroot]# ll /tmp/ |grep sess -rw------- 1 php-fpm php-fpm 37 7月 11 23:37 sess_593f6g4rk451qq0310840boqc0 -rw------- 1 php-fpm php-fpm 37 7月 11 23:35 sess_hldn2qa8n3kmel8tiieckqoj17
4、如果不想将 session 存在 /tmp/ 下,而是存在 memcached 里
那么编辑 php.ini
[root@arslinux-01 wwwroot]# vim /usr/local/php-fpm/etc/php.ini session.save_handler = memcache //指定存储类型 session.save_path = "tcp://192.168.194.130:11211" //指定 memcached 服务器的ip和端口
5、重启 php-fpm,删除 /tmp/下的 session 文件
[root@arslinux-01 wwwroot]# /etc/init.d/php-fpm restart Gracefully shutting down php-fpm . done Starting php-fpm done [root@arslinux-01 wwwroot]# rm -f /tmp/sess_*
6、再 curl 1.php,而 /tmp/ 下已经没有 session 文件生成了
[root@arslinux-01 wwwroot]# curl localhost/1.php 1562859940
1562859940
nf6tt9itt401oq9j7p92rf3663 [root@arslinux-01 wwwroot]# ll /tmp/ |grep sess
7、session 存到了 memcached 里面
[root@arslinux-01 wwwroot]# curl localhost/1.php 1562860064
1562860064
52ofaaoorjjbg4n308tq80kch2
8、直接在 memcached 中查看不了,因为不知道 key
所以可以先 dump 出来,可以看到 key
[root@arslinux-01 wwwroot]# memcached-tool 127.0.0.1:11211 dump >data1.txt Dumping memcache contents Number of buckets: 1 Number of items : 2 Dumping bucket 3 - 2 total items [root@arslinux-01 wwwroot]# cat data1.txt add 52ofaaoorjjbg4n308tq80kch2 0 1562861504 37 TEST|i:1562860064;TEST3|i:1562860064; add nf6tt9itt401oq9j7p92rf3663 0 1562861380 37 TEST|i:1562859940;TEST3|i:1562859940;
或者:
httpd.conf 中对应的虚拟主机中添加(如果安装的是 apache)
php_value session.save_handler "memcache" php_value session.save_path "tcp://192.168.0.9:11211"
或者:
php-fpm.conf 对应的pool中添加(pool 在 /usr/local/php-fpm/etc/php-fpm.d/ 下)
php_value[session.save_handler] = memcache
php_value[session.save_path] = " tcp://192.168.0.9:11211 "
9、重新测试
[root@arslinux-01 wwwroot]# telnet 127.0.0.1 11211 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. get 52ofaaoorjjbg4n308tq80kch2 VALUE 52ofaaoorjjbg4n308tq80kch2 0 37 TEST|i:1562860064;TEST3|i:1562860064; END get nf6tt9itt401oq9j7p92rf3663 VALUE nf6tt9itt401oq9j7p92rf3663 0 37 TEST|i:1562859940;TEST3|i:1562859940; END
数值一致,成功!!!