鲁春利的工作笔记,谁说程序员不能有文艺范?



官方网站:http://redis.io/

下载地址:http://redis.io/download

中文帮助:http://www.redis.cn/


Redis是一种面向“键/值”对数据类型的内存数据库,可以满足我们对海量数据的读写需求。

redis的键只能是字符串;

redis的值支持多种数据类型:

1:字符串 string

2:哈希 hash

3:字符串列表 list 

4:字符串集合 set 不重复,无序

5:有序集合sorted set  ,不重复,有序

6:HyperLogLog 结构(redis2.8.9版本之后才有,用来做基数统计的算法。)


特点:

高性能(Redis读的速度是11W次/s,写的速度是8.1W次/s)

原子性(保证数据的准确性)

持久存储(两种方式RDB/快照,AOF/日志)

主从结构(master-slave,负载均衡,高可用)

支持集群(3.0版本)


应用:应用在高并发和实时请求的场景。

新浪微博

hash:关注列表,粉丝列表

string:微博数,粉丝数(避免使用select count(*) from...)

sorted set:TopN,热门微博

还有github,stackoverflow等也用到了redis    


下载版本:redis-3.0.5.tar.gz


将该tar文件拷贝到/usr/local目录下

# 解压
tar -xzv -f redis-3.0.5.tar.gz
mv redis-3.0.5 redis3.0.5
cd redis3.0.5

# 编译安装
make
make install

# 单机版安装完成

会在/usr/local/bin目录下生成redis的执行命令

[root@nnode bin]# ll
total 15468
-rw-r--r-- 1 root root 29      Nov  8 11:45 dump.rdb
-rwxr-xr-x 1 root root 4587315 Nov  7 23:16 redis-benchmark
-rwxr-xr-x 1 root root 22177   Nov  7 23:16 redis-check-aof
-rwxr-xr-x 1 root root 45395   Nov  7 23:16 redis-check-dump
-rwxr-xr-x 1 root root 4691466 Nov  7 23:16 redis-cli
lrwxrwxrwx 1 root root 12      Nov  7 23:16 redis-sentinel -> redis-server
-rwxr-xr-x 1 root root 6464797 Nov  7 23:16 redis-server



启动redis:

# /usr/local/bin目录已经存在于path路径中,可以直接调用该目录下的文件
[root@nnode redis3.0.5]# redis-server
14469:C 08 Nov 19:03:38.817 # 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.0.5 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 14469
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

14469:M 08 Nov 19:03:38.855 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
14469:M 08 Nov 19:03:38.856 # Server started, Redis version 3.0.5
14469:M 08 Nov 19:03:38.856 # 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.
14469:M 08 Nov 19:03:38.856 # 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.
14469:M 08 Nov 19:03:38.890 * DB loaded from disk: 0.034 seconds
14469:M 08 Nov 19:03:38.890 * The server is now ready to accept connections on port 6379

    此时redis是启在前台的,如果需要停止服务,只需要Ctrl+C即可:

^C14469:signal-handler (1446980678) Received SIGINT scheduling shutdown...
14469:M 08 Nov 19:04:38.334 # User requested shutdown...
14469:M 08 Nov 19:04:38.334 * Saving the final RDB snapshot before exiting.
14469:M 08 Nov 19:04:38.337 * DB saved on disk
14469:M 08 Nov 19:04:38.337 # Redis is now ready to exit, bye bye...


这种启动方式是非常不方便的,还是希望启动在后台,可以通过修改配置文件redis.conf来控制:

# 修改配置redis.conf:
daemonize yes(后台运行)
logfile /usr/local/redis3.0.5/logs/redis-log.out(日志文件,目录必须存在)


启动:

[root@nnode redis3.0.5]# redis-server /usr/local/redis3.0.5/redis.conf 
[root@nnode redis3.0.5]# ps -ef|grep redis
root     14478     1  0 19:04 ?        00:00:00 redis-server *:6379                          
root     14482 11570  0 19:05 pts/0    00:00:00 grep redis
[root@nnode redis3.0.5]#


客户端验证:

[root@nnode redis3.0.5]# redis-cli
127.0.0.1:6379> set name zs
OK
127.0.0.1:6379> get name
"zs"
127.0.0.1:6379> exit

# 或者
redis-cli [-h 127.0.0.1][-p 6379]


关闭Redis:

[root@nnode redis3.0.5]# redis-cli
127.0.0.1:6379> shutdown
not connected> exit

[root@nnode redis3.0.5]# redis-cli shutdown


可以查看redis-server和redis-cli的帮助来了解其具体使用:

# redis-server
[root@nnode redis3.0.5]# redis-server --help
Usage: ./redis-server [/path/to/redis.conf] [options]
       ./redis-server - (read config from stdin)
       ./redis-server -v or --version
       ./redis-server -h or --help
       ./redis-server --test-memory <megabytes>

Examples:
       ./redis-server (run the server with default conf)
       ./redis-server /etc/redis/6379.conf
       ./redis-server --port 7777
       ./redis-server --port 7777 --slaveof 127.0.0.1 8888
       ./redis-server /etc/myredis.conf --loglevel verbose

Sentinel mode:
       ./redis-server /etc/sentinel.conf --sentinel
       
# redis-cli
[root@nnode redis3.0.5]# redis-cli --help
redis-cli 3.0.5

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 N 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*'

  (Note: when using --eval the comma separates KEYS[] from ARGV[] items)

When no command is given, redis-cli starts in interactive mode.
Type "help" in interactive mode for information on available commands.


Redis默认支持16个数据库,其序号为0-15:

# 在redis.conf的配置文件中默认配置如下
# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16

    可以通过修改redis.conf中databases文件修改其支持的数据库个数;

    序号是固定的,不支持自定义序号;

    redis默认选中的是0号数据库;

    SELECT 数字可以切换数据库;

    多个数据库之间不是完全隔离,flushall能够清理所有数据。

[root@nnode redis3.0.5]# redis-cli 
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> set name zs
OK
127.0.0.1:6379> get name
"zs"
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> get name
(nil)
127.0.0.1:6379[1]> set name li
OK
127.0.0.1:6379[1]> get name
"li"
127.0.0.1:6379[1]> select 0
OK
127.0.0.1:6379> get name
"zs"
127.0.0.1:6379> select 16
(error) ERR invalid DB index
127.0.0.1:6379> flushall
OK
127.0.0.1:6379> select 0
OK
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> exit
# flushall之后数据库0和1的值都被清理了。
[root@nnode redis3.0.5]#