linux运维、架构之路-redis

一、redis介绍

          Redis是一个开源,高级的键值存储和一个适用的解决方案,用于构建高性能,可扩展的Web应用程序。

Redis属于非关系型数据库和Memcached类似,redis也是一个key-value型存储系统。但redis支持的存储value类型相对更多,包括string(字符串)、list(列表)、set(集合)和zset(有序集合)等。这些数据类型都支持push/pop、add/remove及取交集、并集和差集及更丰富的操作,而且这些操作都是原子性的。为了保证效率,redis的数据都是缓存在内存中。区别是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在基础上实现了master-slave(主从)同步。 

Redis官方网网站是:http://www.redis.io/ 

Redis中文资料网站:https://redis.io/topics/problems

1、redis特点:

①、支持内存缓存,这个功能相当于memcached
②、支持持久化存储,这个功能相当于memcachedb,ttserver
③、数据库类型更丰富。比其他key-value库功能更强
④、支持主从集群、分布式
⑤、支持队列等特殊功能

2、Redis和Memecache的不同

①、存储方式:
memecache 把数据全部存在内存之中,断电后会挂掉,数据不能超过内存大小, Redis有部份存在硬盘上,这样能保证数据的持久性,支持数据的持久化(笔者注:有RDB快照和AOF日志两种持久化方式,在实际应用的时候,要特别注意配置文件快照参数,要不就很有可能服务器频繁满载做dump)
②、数据支持类型:
redis在数据支持上要比memecache多的多。
③、使用底层模型不同
新版本的redis直接自己构建了VM 机制,因为一般的系统调用系统函数的话,会浪费一定的时间去移动和请求。
④、运行环境不同
redis目前官方只支持Linux 上去行,从而省去了对于其它系统的支持,这样的话可以更好的把精力用于本系统环境上的优化

3、Redis支持的键值类型

String 字符串
Hash  哈希
List    列表
Set    集合
Zset  有序集合

二、部署安装redis

1、环境

[root@redis ~]# cat /etc/redhat-release 
CentOS release 6.9 (Final)
[root@redis ~]# uname -r
2.6.32-696.el6.x86_64
[root@redis ~]# /etc/init.d/iptables status
iptables: Firewall is not running.
[root@redis ~]# getenforce 
Disabled

2、安装

mkdir /server/tools -p
cd /server/tools/
wget http://download.redis.io/releases/redis-3.2.8.tar.gz
tar xf redis-3.2.8.tar.gz 
cd redis-3.2.8
make
make PREFIX=/usr/local/redis–3.2.8  install
ln -s /usr/local/redis–3.2.8 /usr/local/redis
echo "export PATH=/usr/local/redis/bin:$PATH" >>/etc/profile
source  /etc/profile

3、安装目录文件介绍

[root@redis ~]# tree /usr/local/redis/bin/
/usr/local/redis/bin/
├── redis-benchmark           #redis性能读写测试工具
├── redis-check-aof           #对更新日志appenonly.aof检查,类似于mysql binlog
├── redis-check-rdb           #用于本地数据库rdb文件的检查
├── redis-cli                 #redis命令行客户端操作工具
├── redis-sentinel -> redis-server
└── redis-server              #redis服务器daemon启动程序

4、创建redis配置文件目录

启动redis

mkdir /usr/local/redis/conf/ -p                                    #创建配置文件目录
cp -a /server/tools/redis-3.2.8/redis.conf /usr/local/redis/conf/  #拷贝配置文件
redis-server /usr/local/redis/conf/redis.conf &                    #启动redis

启动成功如下:

[root@redis ~]# 4876:C 15 May 14:16:39.704 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.2.8 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 4876
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

4876:M 15 May 14:16:39.708 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
4876:M 15 May 14:16:39.708 # Server started, Redis version 3.2.8
4876:M 15 May 14:16:39.708 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
4876:M 15 May 14:16:39.708 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
4876:M 15 May 14:16:39.708 * The server is now ready to accept connections on port 6379

关闭redis

①使用redis自带脚本:redis-cli shutdown
②ps –ef|grep redis 进行kill杀掉进程

5、redis配置文件详解

daemonize yes                              #是否以后台进程运行
pidfile /var/run/redis/redis-server.pid    #pid文件位置
port 6379                                  #监听端口
bind 127.0.0.1                             #绑定地址,如外网需要连接,设置0.0.0.0 空格分隔
timeout 300                                #连接超时时间,单位秒
loglevel notice                            #日志级别,分别有:
        # debug :适用于开发和测试
        # verbose :更详细信息
        # notice :适用于生产环境
        # warning :只记录警告或错误信息
logfile /var/log/redis/redis-server.log     #日志文件位置
syslog-enabled no                           #是否将日志输出到系统日志
databases 16                                #设置数据库数量,默认数据库为0
############### 快照方式 ###############
    save 900 1                              #在900s(15m)之后,至少有1个key发生变化,则快照
    save 300 10                             #在300s(5m)之后,至少有10个key发生变化,则快照
    save 60 10000                           #在60s(1m)之后,至少有1000个key发生变化,则快照
    rdbcompression yes                      #dump时是否压缩数据
    dir /var/lib/redis                      #数据库(dump.rdb)文件存放目录
############### 主从复制 ###############
    slaveof <masterip> <masterport>         #主从复制使用,用于本机redis作为slave去连接主redis
    masterauth <master-password>            #当master设置密码认证,slave用此选项指定master认证密码
    slave-serve-stale-data yes              #当slave与master之间的连接断开或slave正在与master进行数据同步时,如果有slave请求,当设置为yes时,slave仍然响应请求,此时可能有问题,如果设置no时,slave会返回"SYNC with master in progress"错误信息。但INFO和SLAVEOF命令除外。
############### 安全 ###############
    requirepass foobared                    #配置redis连接认证密码
############### 限制 ###############
    maxclients 128                          #设置最大连接数,0为不限制
    maxmemory <bytes>                       #内存清理策略,如果达到此值,将采取以下动作:
        # volatile-lru      默认策略,只对设置过期时间的key进行LRU算法删除
        # allkeys-lru       删除不经常使用的key
        # volatile-random   随机删除即将过期的key
        # allkeys-random    随机删除一个key
        # volatile-ttl      删除即将过期的key
        # noeviction        不过期,写操作返回报错
    maxmemory-policy volatile-lru          #如果达到maxmemory值,采用此策略
    maxmemory-samples 3                    #默认随机选择3个key,从中淘汰最不经常用的
############### 附加模式 ###############
    appendonly no                          #AOF持久化,是否记录更新操作日志,默认redis是异步(快照)把数据写入本地磁盘
    appendfilename appendonly.aof          #指定更新日志文件名
        # AOF持久化三种同步策略:
        # appendfsync always               #每次有数据发生变化时都会写入appendonly.aof
        # appendfsync everysec             #默认方式,每秒同步一次到appendonly.aof
        # appendfsync no                   #不同步,数据不会持久化
    no-appendfsync-on-rewrite no           #当AOF日志文件即将增长到指定百分比时,redis通过调用BGREWRITEAOF是否自动重写AOF日志文件。
############### 虚拟内存 ###############
    vm-enabled no                          #是否启用虚拟内存机制,虚拟内存机将数据分页存放,把很少访问的页放到swap上,内存占用多,最好关闭虚拟内存
    vm-swap-file /var/lib/redis/redis.swap#虚拟内存文件位置
    vm-max-memory 0                       #redis使用的最大内存上限,保护redis不会因过多使用物理内存影响性能
    vm-page-size 32                       #每个页面的大小为32字节
    vm-pages 134217728                    #设置swap文件中页面数量
    vm-max-threads 4                      #访问swap文件的线程数
############### 高级配置 ###############
    hash-max-zipmap-entries 512           #哈希表中元素(条目)总个数不超过设定数量时,采用线性紧凑格式存储来节省空间
    hash-max-zipmap-value 64              #哈希表中每个value的长度不超过多少字节时,采用线性紧凑格式存储来节省空间
    list-max-ziplist-entries 512          #list数据类型多少节点以下会采用去指针的紧凑存储格式
    list-max-ziplist-value 64             #list数据类型节点值大小小于多少字节会采用紧凑存储格式
    set-max-intset-entries 512            #set数据类型内部数据如果全部是数值型,且包含多少节点以下会采用紧凑格式存储
    activerehashing yes                   #是否激活重置哈希

三、redis主从搭建

1、Master节点

cp -a /server/tools/redis-3.2.8/redis.conf /usr/local/redis/conf/6379.conf
修改配置文件如下:
daemonize no 
修改为:
daemonize yes  #后台程序方式运行

启动Master:

redis-server /usr/local/redis/conf/6379.conf
[root@redis ~]# ps aux|grep redis
root       5005  0.0  0.9 135592  9720 ?        Ssl  14:44   0:04 redis-server 127.0.0.1:6379

2、配置slave节点

cp -a /server/tools/redis-3.2.8/redis.conf /usr/local/redis/conf/6380.conf
修改配置文件如下:
daemonize no 修改为:daemonize yes
port 6379
修改为:
port 6380
增加一行:
slaveof 127.0.0.1 6379

启动Slave

redis-server /usr/local/redis/conf/6380.conf
[root@redis ~]# ps aux|grep redis
root       5014  0.0  0.7 133544  7656 ?        Ssl  14:47   0:04 redis-server 127.0.0.1:6380 

3、查看redis主从同步信息

     启动redis客户端连接6379和6380两个实例

[root@redis ~]# redis-cli  -h 127.0.0.1 -p 6379
127.0.0.1:6379> 
[root@redis ~]# redis-cli  -h 127.0.0.1 -p 6380
127.0.0.1:6380>

①主节点输入info

[root@redis ~]# redis-cli  -h 127.0.0.1 -p 6379
127.0.0.1:6379> info

②从节点输入info

 

4、测试

主节点:

127.0.0.1:6379> set name lulu
OK
127.0.0.1:6379> get name
"lulu"

从节点:

127.0.0.1:6380> get name
"lulu"

###至此两个实例实现了数据同步###

四、生产中单机版配置文件

[root@CTC-CaaS-Master01 conf]# egrep -v "#|^$" redis.conf 
bind 192.168.166.4
port 6379
protected-mode yes
port 6379
tcp-backlog 511
timeout 15
tcp-keepalive 300
daemonize yes
supervised no
pidfile /var/run/redis_6379.pid
loglevel notice
logfile "/data/redis-5.0.6/log/redis-server.log"
databases 16
always-show-logo yes
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir ./
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
replica-priority 100
requirepass Harbor12345
maxclients 10000
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes

 

posted @ 2018-05-15 16:16  闫新江  阅读(530)  评论(0编辑  收藏  举报