Redis配置使用及命令应用实例

Redis配置使用及命令应用实例

1、安装配置使用Redis

[root@test ~]# yum localinstalljemalloc-3.6.0-1.el6.art.x86_64.rpm

Installed:

 jemalloc.x86_64 0:3.6.0-1.el6.art                                                                                                                                   

[root@test ~]# yum localinstallredis-3.2.11-1.el6.x86_64.rpm

Installed:

 redis.x86_64 0:3.2.11-1.el6                                                                                                                                         

Redis安装后文件

[root@test ~]# rpm -ql redis

/etc/logrotate.d/redis

/etc/rc.d/init.d/redis

/etc/rc.d/init.d/redis-sentinel

/etc/redis-sentinel.conf

/etc/redis.conf

/etc/security/limits.d/95-redis.conf

/usr/bin/redis-benchmark

/usr/bin/redis-check-aof

/usr/bin/redis-check-rdb

/usr/bin/redis-cli

/usr/bin/redis-sentinel

/usr/bin/redis-server

/usr/libexec/redis-shutdown

/usr/share/doc/redis-3.2.11

/usr/share/doc/redis-3.2.11/00-RELEASENOTES

/usr/share/doc/redis-3.2.11/BUGS

/usr/share/doc/redis-3.2.11/CONTRIBUTING

/usr/share/doc/redis-3.2.11/COPYING

/usr/share/doc/redis-3.2.11/MANIFESTO

/usr/share/doc/redis-3.2.11/README.md

/usr/share/man/man1/redis-benchmark.1.gz

/usr/share/man/man1/redis-check-aof.1.gz

/usr/share/man/man1/redis-check-rdb.1.gz

/usr/share/man/man1/redis-cli.1.gz

/usr/share/man/man1/redis-sentinel.1.gz

/usr/share/man/man1/redis-server.1.gz

/usr/share/man/man5/redis-sentinel.conf.5.gz

/usr/share/man/man5/redis.conf.5.gz

/var/lib/redis

/var/log/redis

/var/run/redis

Redis守护进程:

         监听端口:6379/tcp

基础使用只需该绑定ip和守护进程:  

[root@test ~]# vi /etc/redis.conf

bind 127.0.0.1192.168.88.130

daemonize yes

[root@test ~]# service redis start

启动:[确定]

[root@test ~]# ss -tnl|grep 6379

0     128              192.168.88.130:6379                          *:*    

0     128                   127.0.0.1:6379                         *:*    

2、Redis客户端命令:redis-cli

[root@test ~]# redis-cli -h

redis-cli 3.2.11

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 andport).

  -a <password>      Password to use when connecting to theserver.

  -r <repeat>        Execute specified command N times.

  -i <interval>      When -r is used, waits <interval>seconds per command.

                     It is possible to specifysub-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 whenSTDOUT is not a tty.

  --csv              Output in CSV format.

  --stat             Print rolling stats about server:mem, clients, ...

  --latency          Enter a special mode continuouslysampling latency.

  --latency-history  Like --latency but tracking latency changesover time.

                     Default time interval is15 sec. Change it using -i.

  --latency-dist     Shows latency as a spectrum, requiresxterm 256 colors.

                     Default time interval is 1sec. Change it using -i.

  --lru-test <keys>  Simulate a cache workload with an 80-20distribution.

  --slave            Simulate a slave showing commandsreceived from the master.

  --rdb <filename>   Transfer an RDB dump from remote server tolocal file.

  --pipe             Transfer raw Redis protocol fromstdin to server.

  --pipe-timeout <n> In --pipe mode,abort with error if after sending all data.

                     no reply is receivedwithin <n> seconds.

                     Default timeout: 30. Use 0to wait forever.

  --bigkeys         Sample Redis keys looking forbig keys.

  --scan             List all keys using the SCANcommand.

  --pattern <pat>    Useful with --scan to specify a SCANpattern.

  --intrinsic-latency <sec> Run a test tomeasure intrinsic system latency.

                     The test will run for thespecified amount of seconds.

  --eval <file>      Send an EVAL command using the Lua scriptat <file>.

  --ldb              Used with --eval enable the RedisLua debugger.

  --ldb-sync-mode    Like --ldb but uses the synchronous Luadebugger, in

                     this mode the server isblocked and script changes are

                     are not rolled back fromthe server memory.

  --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 startsin interactive mode.

Type "help" in interactive modefor information on available commands

and settings.

[root@test ~]# redis-cli

127.0.0.1:6379> exit

[root@test ~]# redis-cli -h 192.168.88.130

192.168.88.130:6379> exit

[root@test ~]# redis-cli -h 192.168.88.130

192.168.88.130:6379> help

redis-cli 3.2.11

To get help about Redis commands type:

     "help @<group>" to get a list of commands in<group>

     "help <command>" for help on <command>

     "help <tab>" to get a list of possible help topics

     "quit" to exit

To set redis-cli perferences:

     ":set hints" enable online hints

      ":set nohints" disable online hints

Set your preferences in ~/.redisclirc

192.168.88.130:6379> help @server

192.168.88.130:6379> CLIENT LIST

id=6 addr=192.168.88.130:45313 fd=6 name=age=86 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0oll=0 omem=0 events=r cmd=client

192.168.88.130:6379>

SELECT:打开多个数据库,即多个名称空间。

在同一个名称空间内键不能重复,键是可以实现自动过期的

192.168.88.130:6379> select  1     

OK

192.168.88.130:6379[1]> select  2

OK

192.168.88.130:6379[2]> select  0

OK

192.168.88.130:6379>

3、Redis数据类型及其命令使用

(1).String(字符串)

192.168.88.130:6379> help @string

         SET: 将字符串值 value 关联到 key 。如果 key 已经持有其他值, SET 就覆写旧值,无视类型。

  SET key value [EX seconds] [PX milliseconds][NX|XX]

                   [EX seconds] 过期时间等价SETEX 

                   [NX|XX]    EX:键不存在才创建并设置值,否则不创建。XX:健存在才设定       SET:

         GET:返回 key 所关联的字符串值。如果 key 不存在那么返回特殊值 nil 。假如 key 储存的值不是字符串类型,返回一个错误,因为 GET 只能用于处理字符串值。

         APPEND:如果 key 已经存在并且是一个字符串, APPEND 命令将 value 追加到 key 原来的值的末尾。如果 key 不存在, APPEND 就简单地将给定 key 设为 value ,就像执行 SET key value 一样。   

         INCR:将 key 中储存的数字值增一。如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。        

         DECR:将 key 中储存的数字值减一。如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 DECR 操作。

192.168.88.130:6379> set disco federa

OK

192.168.88.130:6379> get disco

"federa"

192.168.88.130:6379> set disco centos

OK

192.168.88.130:6379> get disco

"centos"

192.168.88.130:6379> append discoslackware

(integer) 15

192.168.88.130:6379> get disco

"centosslackware"

192.168.88.130:6379> SET disco gentoo NX

(nil)

192.168.88.130:6379> GET disco

"centosslackware"

192.168.88.130:6379> SET foo bar XX

(nil)

192.168.88.130:6379> STRLEN disco

(integer) 15

192.168.88.130:6379> set count 0

OK

192.168.88.130:6379> incr count

(integer) 1

192.168.88.130:6379> incr count

(integer) 2

192.168.88.130:6379> decr count

(integer) 1

192.168.88.130:6379> decr count

(integer) 0

192.168.88.130:6379> set foo bar

OK

192.168.88.130:6379> incr foo

(error) ERR value is not an integer or outof range

(2).List(列表)

192.168.88.130:6379> HELP @LIST

         LSET:         LSET keyindex value 将列表 key 下标为 index 的元素的值设置为 value 。当 index 参数超出范围,或对一个空列表( key 不存在)进行 LSET 时,返回一个错误

         LPUSH:LPUSH key value [value ...] 将一个或多个值 value 插入到列表 key 的表头

                                     如果有多个 value 值,那么各个 value 值按从左到右的顺序依次插入到表头:比如说,对空列表 mylist 执行命令 LPUSH mylist a b c ,列表的值将是 c b a ,这等同于原子性地执行 LPUSH mylist a、 LPUSH mylist b 和 LPUSH mylist c 三个命令。

         RPUSH:RPUSH key value [value ...] 将一个或多个值 value 插入到列表 key 的表尾(最右边)。

                                     如果有多个 value 值,那么各个 value 值按从左到右的顺序依次插入到表尾:比如对一个空列表 mylist 执行 RPUSH mylist a b c ,得出的结果列表为 a b c ,等同于执行命令 RPUSH mylist a 、 RPUSH mylist b 、 RPUSH mylist c 。

         LPOP:移除并返回列表 key 的头元素。     

         RPOP:移除并返回列表 key 的尾元素。    

         LINDEX:LINDEX key index 返回列表 key 中,下标为 index 的元素。   

         LLEN:返回列表 key 的长度。如果 key 不存在,则 key 被解释为一个空列表,返回 0。如果 key 不是列表类型,返回一个错误。

192.168.88.130:6379> lpush l1 mon

(integer) 1

192.168.88.130:6379> lindex l1 0

"mon"

192.168.88.130:6379> lpush l1 sun

(integer) 2

192.168.88.130:6379> lindex l1 0

"sun"

192.168.88.130:6379> lindex l1 1

"mon"

192.168.88.130:6379> rpush l1 tue

(integer) 3

192.168.88.130:6379> lindex l1 2

"tue"

192.168.88.130:6379> lset l1 fri

(error) ERR wrong number of arguments for'lset' command

192.168.88.130:6379> lset l1 1 fri

OK

192.168.88.130:6379> lindex l1 1

"fri"

192.168.88.130:6379> rpop l1

"tue"

192.168.88.130:6379> rpop l1

"fri"

192.168.88.130:6379> rpop l1

"sun"

192.168.88.130:6379> rpop l1

(nil)

(3).集合(Sets):

192.168.88.130:6379> HELP @SET        

         SADD:SADD key member [member ...] 将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略。假如 key 不存在,则创建一个只包含 member 元素作成员的集合。

         SISMEMBER:SISMEMBER key member 判断 member 元素是否集合 key 的成员。

         SINTER:SINTER key [key ...] 返回一个集合的全部成员,该集合是所有给定集合的交集。不存在的 key 被视为空集。

         SINTERSTORE:SINTERSTORE destination key [key ...] 这个命令类似于 SINTER 命令,但它将结果保存到 destination 集合,而不是简单地返回结果集。如果destination 集合已经存在,则将其覆盖。 

         SUNION:SUNION key [key ...] 返回一个集合的全部成员,该集合是所有给定集合的并集。不存在的 key 被视为空集。

         SUNIONSTORE:SUNIONSTORE destination key [key ...] 这个命令类似于 SUNION 命令,但它将结果保存到 destination 集合,而不是简单地返回结果集。如果destination 已经存在,则将其覆盖。

         SDIFF:SDIFF key [key ...] 返回一个集合的全部成员,该集合是所有给定集合之间的差集。不存在的 key 被视为空集。

         SDIFFSTORE:SDIFFSTORE destination key [key ...]吧这个命令的作用和 SDIFF 类似,但它将结果保存到 destination 集合,而不是简单地返回结果集。如果destination 集合已经存在,则将其覆盖。

         SPOP:移除并返回集合中的一个随机元素。如果只想获取一个随机元素,但不想该元素从集合中被移除的话,可以使用 SRANDMEMBER 命令。

        

192.168.88.130:6379> sadd w1 mon tue wedthu fri sat sun

(integer) 7

192.168.88.130:6379> sadd w2 tue thu day

(integer) 3

192.168.88.130:6379> sinter w1 w2  取交集

1) "thu"

2) "tue"

192.168.88.130:6379> sunion w1 w2  取并集

1) "mon"

2) "day"

3) "sat"

4) "fri"

5) "thu"

6) "tue"

7) "sun"

8) "wed"

192.168.88.130:6379> spop w1               弹出元素,随机    

"sat"

192.168.88.130:6379> spop w1

"sun"

192.168.88.130:6379> SDIFF w1 w2       取差集

1) "wed"

2) "fri"

3) "mon"

192.168.88.130:6379> SDIFF w2 w1

1) "day"

192.168.88.130:6379> sismember w1mon  元素在不在集合中

(integer) 1

192.168.88.130:6379> sismember w1 xx

(integer) 0

192.168.88.130:6379>

(4).SortedSet(有序集合)

192.168.88.130:6379> help @SORTED_SET

         ZADD:ZADD key [NX|XX] [CH] [INCR] score member [score member...] 将一个或多个 member 元素及其 score 值加入到有序集 key 当中。

         ZRANGE:ZRANGE key start stop [WITHSCORES] 返回有序集 key 中,指定区间内的成员。其中成员的位置按 score 值递增(从小到大)来排序

         ZCARD:返回有序集 key 的基数。

         ZRANK:返回有序集 key 中成员 member 的排名。其中有序集成员按 score 值递增(从小到大)顺序排列。排名以 0 为底,也就是说, score 值最小的成员排名为 0

192.168.88.130:6379> zadd weekday1 1 mon2 tue 3 wed

(integer) 3

192.168.88.130:6379> zcard weekday1

(integer) 3

192.168.88.130:6379> zrank weekday1 tue

(integer) 1

192.168.88.130:6379> zrank weekday1 wed

(integer) 2

192.168.88.130:6379> zscore weekday1 wed

"3"

192.168.88.130:6379> zscore weekday1 tue

"2"

192.168.88.130:6379> zrange weekday1 0 2

1) "mon"

2) "tue"

3) "wed"

192.168.88.130:6379> zrange weekday1 0 1

1) "mon"

2) "tue"

(5).Hash(哈希表)

192.168.88.130:6379> help @hash

         HSET:HSET key field value将哈希表 key 中的域 field 的值设为 value 。如果 key 不存在,一个新的哈希表被创建并进行 HSET 操作。如果域 field 已经存在于哈希表中,旧值将被覆盖。

         HSETNX:HSETNX key field value 将哈希表 key 中的域 field 的值设置为 value ,当且仅当域 field 不存在。若域 field 已经存在,该操作无效。

         HGET:返回哈希表 key 中给定域 field 的值。

         HKEYS:返回哈希表 key 中的所有键。

         HVALS:返回哈希表 key 中所有键的值。

         HDEL:删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。

 

192.168.88.130:6379> HSET h1 a mon

(integer) 1

192.168.88.130:6379> hget h1 a

"mon"

192.168.88.130:6379> hset h1 b tue

(integer) 1

192.168.88.130:6379> hget h1 b

"tue"

192.168.88.130:6379> hkeys h1

1) "a"

2) "b"

192.168.88.130:6379> HVALS h1

1) "mon"

2) "tue"

192.168.88.130:6379> hlen h1

(integer) 2

192.168.88.130:6379> HDEL h1 a

(integer) 1

192.168.88.130:6379> hget h1 a

(nil)

192.168.88.130:6379>

4、其他常用命令

(1)、事务:将多个命令打包而后一次性执行,执行期间其他事务命令会阻塞。

将多个命令、请求打包成一个操作然后一次性按顺序执行多个命令的机制,

并且在事务执行期间服务器不会中断事务而改变去执行其他客户端事务命令的请求,

会将事务中所有命令执行完毕再去执行其他服务器事务请求。

         通过MULTI,EXEC,WATCH等命令实现事务功能;将一个或多个命令归并为一个操作提请服务按顺序执行的机制;不支持回滚。

         MULTI:启动一个事物

         EXEC:执行事务

                            一次性将事务中的所有操作执行完成后返回给客户端

         WATCH:乐观锁;在EXEC命令执行之前,用于监视指定数量键;如果监视中的某任意键数据被修改,则服务器拒绝执行事务;

执行事务

192.168.88.130:6379> MULTI

OK

192.168.88.130:6379> set ip 192.168.88.2

QUEUED

192.168.88.130:6379> get ip

QUEUED

192.168.88.130:6379> set port 80

QUEUED

192.168.88.130:6379> get ip

QUEUED

192.168.88.130:6379> EXEC

1) OK

2) "192.168.88.2"

3) OK

4) "192.168.88.2"

192.168.88.130:6379>

监视某键值

192.168.88.130:6379> WATCH ip

OK

192.168.88.130:6379> MULTI

OK

         此期间打开其他客户端,设置ip值

         [root@test~]# redis-cli -h 192.168.88.130

         192.168.88.130:6379>SET ip 172.16.100.1

         OK

         192.168.88.130:6379>GET ip

         "172.16.100.1"

         192.168.88.130:6379>

192.168.88.130:6379> SET ip 192.168.88.1

QUEUED

192.168.88.130:6379> GET IP

QUEUED

192.168.88.130:6379> GET ip

QUEUED

192.168.88.130:6379> EXEC

(nil)

192.168.88.130:6379>

不支持回滚:

192.168.88.130:6379> MULTI

OK

192.168.88.130:6379> get ip

QUEUED

192.168.88.130:6379> set port 6379

QUEUED

192.168.88.130:6379> setttt

(error) ERR unknown command 'setttt'

192.168.88.130:6379> exec

(error) EXECABORT Transaction discardedbecause of previous errors.

192.168.88.130:6379>

(2).connection相关的命令

192.168.88.130:6379> HELP @connection

192.168.88.130:6379> ping 192.168.88.130

"192.168.88.130"

192.168.88.130:6379> echo "helloworld!"

"hello world!"

(3).Server相关的命令:

192.168.88.130:6379> help @server

  BGREWRITEAOF - 执行一个 AOF文件重写操作。重写会创建一个当前 AOF 文件的体积优化版本。

         BGSAVE - 在后台异步(Asynchronously)保存当前数据库的数据到磁盘。、

  CLIENT GETNAME - 获取当前客户端名字

192.168.88.130:6379>CLIENT GETNAME

"fieldconn" 

  CLIENT KILL [ip:port] [ID client-id] [TYPEnormal|master|slave|pubsub] [ADDR ip:port] [SKIPME yes/no]

       指明IP+端口直接关闭对应的客户端连接信息

  CLIENT LIST - 以人类可读的格式,返回所有连接到服务器的客户端信息和统计数据。

192.168.88.130:6379> client list

id=4 addr=192.168.88.130:45351 fd=7 name=age=2279 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0oll=0 omem=0 events=r cmd=client

id=5 addr=192.168.88.130:45353 fd=6 name=age=588 idle=361 flags=O db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0oll=0 omem=0 events=r cmd=monitor

192.168.88.130:6379>

  CLIENT SETNAMEconnection-name 设置客户当前客户端连接名

192.168.88.130:6379> CLIENT SETNAMEfieldconn 

 COMMAND -

       summary: Get array of Redis command details

  CONFIG GET parameter  命令用于取得运行中的 Redis 服务器的配置参数(configuration parameters)

  CONFIG RESETSTAT - 重置info中统计的信息

  CONFIG REWRITE - 内存中修改的参数新值同步到配置文件中

  CONFIG SET parameter value 运行时修改指定参数值,只会保存到内存中,不会保存在配置文件中

  DBSIZE - 显示当前数据库中所有键的数量

192.168.88.130:6379> dbsize

(integer) 2 

  DEBUG OBJECT key 一个调试命令,它不应被客户端所使用。

  DEBUG SEGFAULT - 执行一个不合法的内存访问从而让 Redis 崩溃,仅在开发时用于 BUG 模拟。

FLUSHALL - 清空所有数据库

  FLUSHDB - 清空当前数据库

  INFO [section] 查看服务去状态信息

192.168.88.130:6379> INFO Memory

# Memory

used_memory:832856

used_memory_human:813.34K

used_memory_rss:2351104

used_memory_rss_human:2.24M

used_memory_peak:833608

used_memory_peak_human:814.07K

total_system_memory:340770816

total_system_memory_human:324.98M

used_memory_lua:37888

used_memory_lua_human:37.00K

maxmemory:0

maxmemory_human:0B

maxmemory_policy:noeviction

mem_fragmentation_ratio:2.82

mem_allocator:jemalloc-3.6.0 

  LASTSAVE - 返回最近一次 Redis 成功将数据保存到磁盘上的时间,以 UNIX 时间戳格式表示。

  MONITOR - 实时打印出 Redis 服务器接收到的命令,调试用。

192.168.88.130:6379> monitor

OK

另起客户端执行如下操作    

         192.168.88.130:6379>GET ip

         "172.16.100.1"

         192.168.88.130:6379>SET ip 172.16.100.2

         OK

         192.168.88.130:6379>set port 8080

         OK

1524668084.143270 [0 192.168.88.130:45351]"GET" "ip"

1524668093.083372 [0 192.168.88.130:45351]"SET" "ip" "172.16.100.2"

1524668107.121608 [0 192.168.88.130:45351]"set" "port" "8080"   

  SAVE - SAVE 命令执行一个同步保存操作,将当前 Redis 实例的所有数据快照(snapshot)以 RDB 文件的形式保存到硬盘。

  SHUTDOWN[NOSAVE|SAVE]  把所有数据同步到磁盘后安全的关闭

       SHUTDOWN命令执行以下操作:

    停止所有客户端

    如果有至少一个保存点在等待,执行 SAVE 命令

    如果 AOF 选项被打开,更新 AOF 文件

    关闭 redis 服务器(server)

  SLAVEOF host port 通过执行 SLAVEOF host port 命令,可以将当前服务器转变为指定服务器的从属服务器(slave server)。

  SLAVEOF 命令用于在 Redis 运行时动态地修改复制(replication)功能的行为。

         SLOWLOG subcommand [argument] 显示Redis的慢查询日志

  SYNC - 用于复制功能(replication)的內建命令。

  TIME - 返回当前服务器时间

192.168.88.130:6379> time

1) "1524668303"

2) "814349" 

192.168.88.130:6379>

(4).发布和订阅(publish/subscribe)

         频道:消息队列

         SUBSCRIBE:订阅一个或多个队列

         PUBLISH:像频道发布消息     

         UNSUBSCRIBE:退订此前订阅的频道

         PSUBSCRIBE:模式订阅

SUBSCRIBE和PUBLISH:发布和订阅

192.168.88.130:6379> SUBSCRIBE news

Reading messages... (press Ctrl-C to quit)

1) "subscribe"

2) "news"

3) (integer) 1

其它连接客户端

         192.168.88.130:6379>PUBLISH news hello

         (integer)1

         192.168.88.130:6379>PUBLISH news reida

         (integer)1

1) "message"

2) "news"

3) "hello"

1) "message"

2) "news"

3) "reida"

模式订阅:PSUBSCRIBE

192.168.88.130:6379> PSUBSCRIBEnew.i[to]

Reading messages... (press Ctrl-C to quit)

1) "psubscribe"

2) "new.i[to]"

3) (integer) 1

其它连接客户端

         192.168.88.130:6379>PUBLISH new.io hello

         (integer)1

         192.168.88.130:6379>PUBLISH new.it world

         (integer)1

1) "pmessage"

2) "new.i[to]"

3) "new.io"

4) "hello"

1) "pmessage"

2) "new.i[to]"

3) "new.it"

4) "world"

UNSUBSCRIBE:退订

192.168.88.130:6379> UNSUBSCRIBE new

1) "unsubscribe"

2) "new"

3) (integer) 0

猜你喜欢

转载自blog.csdn.net/field_yang/article/details/80141703
今日推荐