redis --初级笔记

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

Redis

remote directory server (redis),是一个基于key-value键值对的持久化数据库存储系统,redis支持数据的存储更丰富,包括string,list,setzset等。

 这些数据类型都支持push、pop,add,remove及取交集,差集等更丰富的操作,而且这些操作都是原子性的,在此基础上支持不同的排序方式,所有的数据都是保存在内从中的,但是redis的持久化服务还会周期性的吧更新数据写到磁盘以及把修改的操作记录追加到文件里记录下来,比memcached更优势的是,redis还支持master-slave同步,这点很类似关系型数据库mysql。

  redis的出现,在一定程度上弥补了memcached这类key-value内存缓存服务的不足,在部分场合可以对关系型数据库起到补充作用


官方网站www.redis.cn国内

     www.redis.io国外


redis的优点

1,性能很高:redis能支持超过100K(10W)+每秒的读写频率

2,丰富的数据类型:redis支持二进制strings,lists,hashes,sets,及ordered sets等


3,原子:redis的所有操作都是原子型的,同时redis还支持对决几个操作全并后的原子性执行.

4,丰富的特性:redis还支持pushlish subscribe,通知,key过期等特性

5,redis支持异机主从同步复制

6,与memcached不同,可以持久化存储数据



#########redis的应用场景

传统的mysql+memcahed的网站架构遇到的问题:

mysql的数据库实际上是适合进行海量数据存储的,加上通过memcached将热点数据存放到内存cache里,达到加速数访问的目的,绝大部分公司曾经使用这样的架构,但随着业务数据量的不算增加,和访问量的持续增长买很多问题就会暴漏出来:

1,需要不断的对mysql进行拆库,拆表,memcached也需要不断跟着扩容,扩容和维护工作占据大量开发运维时间

2,memcached与mysql的数据一致性问题是个老大难

3,mencached的数据命中率会down机,会导致大量访问直接穿透到数据库,导致mysql无法支撑.(这个是最致命的)

4,跨机房cache同步一致性问题




############redis的最佳应用场景

1,redis最佳使用场景是全部数据in-memory

2,reids更多场景是作为memcached的替代品来使用

3,当需要处key/value之外的更多数据类型支持时候,使用redis更合适

4,当存储的数据不能被踢除时候,使用redis更适合 


redis作者谈redis应用场景http://blog.nosqlfan.com/html/2235.html

redis资料汇总专题:非常全http://blog.nosqlfan.com/html/3537.html



使用redis bitmap进行活跃用户统计:

http://blog,nosqlfan.com/html/3501.html


Redis运维之道:http://blog.nosqlfan.com/html/2692.html?ref=rediszt


redis数据库的小结:

1,提高了DB的可扩展行,只需将新增的数据放到新加的服务器上就可以了

2,提高了DB的可用性,只影响到访问的shard服务器上的数据的用户

3.提高了DB 的可维护性,对系统的升级和配置可以按shard一个个来高,对服务产生的影响比较小

4,当达到最大内存时候,会清空带有过期时间的key,及时key未到过期时间

5,redis与DB同步写的问题,先写DB,后写redis,因为写内存基本上没有问题


################################安装与部署


Redis安装部署 


1. 下载地址:

1
2
3
4
5
6
7
8
$ wget http: //redis .googlecode.com /files/redis-2 .6.13. tar .gz
2. 解压缩
tar  xzf redis-2.6.13. tar .gz
3. 编译
cd  redis-2.6.13
make
$ make  install
$ cp  redis.conf  /etc/

参数介绍:


make install命令执行完成后,会在/usr/local/bin目录下生成本个可执行文件,

分别是redis-server、redis-cli、redis-benchmark、redis-check-aof 、redis-check-dump,

它们的作用如下:

1
2
3
4
5
6
7
8
redis-server:Redis服务器的daemon启动程序
redis-cli:Redis命令行操作工具。也可以用telnet根据其纯文本协议来操作
redis-benchmark:Redis性能测试工具,测试Redis在当前系统下的读写性能
redis-check-aof:数据修复
redis-check-dump:检查导出工具
4. 修改系统配置文件,执行命令
a)  echo  vm.overcommit_memory=1 >>  /etc/sysctl .conf
b) sysctl vm.overcommit_memory=1 或执行 echo  vm.overcommit_memory=1 >> /proc/sys/vm/overcommit_memory

使用数字含义:


0,表示内核将检查是否有足够的可用内存供应用进程使用;如果有足够的可用内存,内存申请允许;否则,内存申请失败,并把错误返回给应用进程。


1,表示内核允许分配所有的物理内存,而不管当前的内存状态如何。


2,表示内核允许分配超过所有物理内存和交换空间总和的内存


5. 修改redis配置文件

1
2
a) $  cd  /etc
b)  vi  redis.conf

c) 修改daemonize yes---目的使进程在后台运行


参数介绍:


daemonize:是否以后台daemon方式运行


pidfile:pid文件位置


port:监听的端口号


timeout:请求超时时间


loglevel:log信息级别


logfile:log文件位置


databases:开启数据库的数量


save * *:保存快照的频率,第一个*表示多长时间,第三个*表示执行多少次写操作。在一定时间内执行一定数量的写操作时,自动保存快照。可设置多个条件。


rdbcompression:是否使用压缩


dbfilename:数据快照文件名(只是文件名,不包括目录)


dir:数据快照的保存目录(这个是目录)


appendonly:是否开启appendonlylog,开启的话每次写操作会记一条log,这会提高数据抗风险能力,但影响效率。


appendfsync:appendonlylog如何同步到磁盘(三个选项,分别是每次写都强制调用fsync、每秒启用一次fsync、不调用fsync等待系统自己同步)


6. 启动redis

1
2
a) $  cd  /usr/local/bin
b) . /redis-server  /etc/redis .conf

7. 检查是否启动成功

1
a) $  ps  -ef |  grep  redis


1,关闭redis服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
[root@localhost ~] # redis-cli 
127.0.0.1:6379>  shutdown
2,useage
[root@localhost ~] # redis-cli --help
redis-cli 3.0.3
Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
   -h < hostname >      Server  hostname  (default: 127.0.0.1).
   -p <port>          Server port (default: 6379).
   -s <socket>        Server socket (overrides  hostname  and port).
   -a <password>      Password to use when connecting to the server.
   -r <repeat>        Execute specified  command  times .
   -i <interval>      When -r is used, waits <interval> seconds per  command .
                      It is possible to specify sub-second  times  like -i 0.1.
   -n <db>            Database number.
   -x                 Read last argument from STDIN.
   -d <delimiter>     Multi-bulk delimiter  in  for  raw formatting (default: \n).
   -c                 Enable cluster mode (follow -ASK and -MOVED redirections).
   --raw              Use raw formatting  for  replies (default when STDOUT is
                      not a  tty ).
   --no-raw           Force formatted output even when STDOUT is not a  tty .
   --csv              Output  in  CSV  format .
   --stat             Print rolling stats about server: mem, clients, ...
   --latency          Enter a special mode continuously sampling latency.
   --latency- history   Like --latency but tracking latency changes over  time .
                      Default  time  interval is 15 sec. Change it using -i.
   --latency-dist     Shows latency as a spectrum, requires xterm 256 colors.
                      Default  time  interval is 1 sec. Change it using -i.
   --lru- test  <keys>  Simulate a cache workload with an 80-20 distribution.
   --slave            Simulate a slave showing commands received from the master.
   --rdb <filename>   Transfer an RDB dump from remote server to  local  file .
   --pipe             Transfer raw Redis protocol from stdin to server.
   --pipe-timeout <n> In --pipe mode, abort with error  if  after sending all data.
                      no reply is received within <n> seconds.
                      Default timeout: 30. Use 0 to wait forever.
   --bigkeys          Sample Redis keys looking  for  big keys.
   --scan             List all keys using the SCAN  command .
   --pattern <pat>    Useful with --scan to specify a SCAN pattern.
   --intrinsic-latency <sec> Run a  test  to measure intrinsic system latency.
                      The  test  will run  for  the specified amount of seconds.
   -- eval  < file >      Send an EVAL  command  using the Lua script at < file >.
   --help             Output this help and  exit .
   --version          Output version and  exit .
Examples:
   cat  /etc/passwd  | redis-cli -x  set  mypasswd
   redis-cli get mypasswd
   redis-cli -r 100 lpush mylist x
   redis-cli -r 100 -i 1 info |  grep  used_memory_human:
   redis-cli -- eval  myscript.lua key1 key2 , arg1 arg2 arg3
   redis-cli --scan --pattern  '*:12345*'
[root@localhost ~] # cd /usr/local/bin/
[root@localhost bin] # ./redis-server /etc/redis.conf 
[root@localhost bin] # redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> 
127.0.0.1:6379> help get
   GET key
   summary: Get the value of a key
   since: 1.0.0
   group: string
127.0.0.1:6379>  set  db. test .username  helloboy 
OK
127.0.0.1:6379> get  db. test .username
"helloboy"
  
127.0.0.1:6379>  set  no002 helloboy 
OK
127.0.0.1:6379> get no002
"helloboy"
[root@localhost ~] # redis-cli -h 127.0.0.1 -p 6379 set 002num lisia
OK
[root@localhost ~] # redis-cli -h 127.0.0.1 -p 6379 get 002num
"lisia"
  
[root@localhost ~] # redis-cli -h 127.0.0.1 -p 6379 get 002num
"lisia"
[root@localhost ~] # redis-cli del  002num
(integer) 1
[root@localhost ~] # redis-cli -h 127.0.0.1 -p 6379 get 002num
(nil)
[root@localhost ~]
[root@localhost ~] # telnet 127.0.0.1 6379
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is  '^]' .
set  no003 jihui
+OK
get no003
$5
jihui


###############字符串类型

这是简单的redis最简单的类型,如果你只用这种类型,redis就是一个可以持久化的memcacehd服务器

下面是字符串类型:

1
2
3
4
[root@localhost ~] # redis-cli  set mykey "my binary safe value"
OK
[root@localhost ~] # redis-cli get mykey
"my binary safe value"

"my binary safe value" 如你所示,通常用set和get来设置和获取字符串值

值可以是任何种类的字符串,(包括二进制数据),例如你可以再一个键下保存一副jpeg图片,值的长度不超过1GB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  
list:
[root@localhost ~] # redis-cli  rpush messages "hello old are you?"
(integer) 1
[A[root@localhost ~] # redis-cli  rpush messages "im fine thank you"
(integer) 2
[root@localhost ~] # redis-cli  rpush messages "and you "
(integer) 3
读取list
[root@localhost ~] # redis-cli  lrange  messages 0 2
1)  "hello old are you?"
2)  "im fine thank you"
3)  "and you "
[root@localhost ~] # redis-cli  lrange  messages 0 1
1)  "hello old are you?"
2)  "im fine thank you"
[root@localhost ~] # redis-cli  lrange  messages 0 0
1)  "hello old are you?"
###########################为php安装redis客户端
wget  https: //github .com /nicolasff/phpredis/archive/master .zip
  unzip master.zip 
  1005   cd  phpredis-master/
  1006   /usr/local/php/bin/phpize 
  1007  . /configure  --with-php-config= /usr/local/php/bin/php-config 
  1008   make 
  1009   make  install
[root@localhost phpredis-master] # make install
Installing shared extensions:      /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/
修改php.ini ,重启php
[root@localhost phpredis-master] # echo "extension=redis.so" >> /usr/local/php/etc/php.ini 
[root@localhost phpredis-master]
[root@localhost phpredis-master] # /etc/init.d/php-fpm restart
Gracefully shutting down php-fpm .  done
Starting php-fpm   done


保存到磁盘

save 900 1     每900秒  1个记录

save 300 10    每300秒   10个记录


 

#####################redis 主从配置:

只需在从redis服务器配置

1
2
slaveof master-ip  master-port
slaveof  192.168.0.110 6379

重启从redis服务即开



###################redis负载均衡

可以使用lvs,像轮询web服务器一样即可


集群案例转载:

http://navyaijm.blog.51cto.com/4647068/1706715






      本文转自crazy_charles 51CTO博客,原文链接:http://blog.51cto.com/douya/1680689,如需转载请自行联系原作者




相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
2月前
|
存储 缓存 NoSQL
蚂蚁金服P7私藏的Redis原理与实践内部笔记
Redis 是完全开源免费的,是一个高性能的key-value类型的内存数据库。整个数据库统统加载在内存当中进行操作,定期通过异步操作把数据库数据flush到硬盘上进行保存。因为是纯内存操作,Redis的性能非常出色,每秒可以处理超过 10万次读写操作,是已知性能最快的Key-Value DB。
59 1
|
3月前
|
NoSQL Redis
Redis原理之网络通信协议笔记
1. RESP协议 ​2. 自定义Socket连接Redis
|
3月前
|
NoSQL Linux Redis
Redis原理之网络模型笔记
Redis采用单线程模型,这意味着一个Redis服务器在任何时刻都只会处理一个请求。Redis的网络模型涉及到阻塞I/O(Blocking I/O)、非阻塞I/O(Non-blocking I/O)、I/O多路复用(I/O Multiplexing)、信号驱动I/O(Signal-driven I/O)以及异步I/O(Asynchronous I/O)。
|
3月前
|
NoSQL Redis
Redis原理之五种数据类型笔记
String List Set ZSet ​ Hash
|
3月前
|
NoSQL Redis C语言
|
3月前
|
存储 移动开发 NoSQL
笔记 - 《Redis深度历险》
《Redis深度历险》的笔记
|
3月前
|
存储 NoSQL Redis
redis基础数据类型常用命令笔记
redis基础数据类型常用命令笔记
14 0
|
3月前
|
缓存 NoSQL Java
公开!腾讯技术专家手撸Redis技术笔记,下载量已突破30W
Redis的火爆程度,相信不用我多说,现在大型的互联网公司基本上都需要使用到Redis技术。Redis作为目前最火爆的内存数据库之一,通过在内存中读写数据,很大程度上提高了读写速度,可以说Redis 是实现网站高并发不可或缺的一部分。
|
4月前
|
NoSQL 安全 Redis
黑马点评笔记 redis实现优惠卷秒杀(二)
黑马点评笔记 redis实现优惠卷秒杀
35 0
|
4月前
|
NoSQL 关系型数据库 MySQL
黑马点评笔记 redis实现优惠卷秒杀(一)
黑马点评笔记 redis实现优惠卷秒杀
50 0