redis入门教程

window平台下的redis dll文件下载:https://github.com/char101/phpredis/downloads

Redis 根据 5 种不同的数据类型来操作数据对象:

String(字符串)
Sets(集合)
zsets( 排序后的sets集合)
List(列表)
hash(哈稀)

操作 String 类型的值:

Command Parameters Description
SET key value Set a key to a string value
GET key Return the string value of the key
GETSET key value Set a key to a string returning the old value of the key
MGET key1 key2 ... keyN Multi-get, return the strings values of the keys
SETNX key value Set a key to a string value if the key does not exist
SETEX key time value Set+Expire combo command
MSET key1 value1 key2 value2 ... keyN valueN Set multiple keys to multiple values in a single atomic operation
MSETNX key1 value1 key2 value2 ... keyN valueN Set multiple keys to multiple values in a single atomic operation if none of the keys already exist
INCR key Increment the integer value of key
INCRBY key integer Increment the integer value of key by integer
DECR key Decrement the integer value of key
DECRBY key integer Decrement the integer value of key by integer
APPEND key value Append the specified string to the string stored at key
SUBSTR key start end Return a substring of a larger string

操作 sets 类型的值:(sets 集合)

Command Parameters Description
SADD key member Add the specified member to the Set value at key
SREM key member Remove the specified member from the Set value at key
SPOP key Remove and return (pop) a random element from the Set value at key
SMOVE srckey dstkey member Move the specified member from one Set to another atomically
SCARD key Return the number of elements (the cardinality) of the Set at key
SISMEMBER key member Test if the specified value is a member of the Set at key
SINTER key1 key2 ... keyN Return the intersection between the Sets stored at key1, key2, ..., keyN
SINTERSTORE dstkey key1 key2 ... keyN Compute the intersection between the Sets stored at key1, key2, ..., keyN, and store the resulting Set at dstkey
SUNION key1 key2 ... keyN Return the union between the Sets stored at key1, key2, ...,keyN
SUNIONSTORE dst key key1 key2 ... keyN Compute the union between the Sets stored atkey1, key2, ..., keyN, and store the resulting Set at dstkey
SDIFF key1 key2 ... keyN Return the difference between the Set stored at key1 and all the Sets key2, ..., keyN
SDIFFSTORE dstkey key1 key2 ... keyN Compute the difference between the Set key1 and all the Sets key2, ..., keyN, and store the resulting Set at dstkey
SMEMBERS key Return all the members of the Set value at key
SRANDMEMBER key Return a random member of the Set value at key

操作 lists 类型的值:(列表)

Command Parameters Description
RPUSH key value Append an element to the tail of the List value at key
LPUSH key value Append an element to the head of the List value at key
LLEN key Return the length of the List value at key
LRANGE key start end Return a range of elements from the List at key
LTRIM key start end Trim the list at key to the specified range of elements
LINDEX key index Return the element at index position from the List at key
LSET key index value Set a new value as the element at index position of the List at key
LREM key count value Remove the first-N, last-N, or all the elements matching value from the List at key
LPOP key Return and remove (atomically) t he first element of the List at key
RPOP key Return and remove (atomically) the last element of the List at key
BLPOP key1 key2 ... keyN timeout Blocking LPOP
BRPOP key1 key2 ... keyN timeout Blocking RPOP
RPOPLPUSH srckey dstkey Return and remove (atomically) the last element of the source List stored at srckey and push the same element to the destination List stored at dstkey

操作 zsets 类型的值:(排序后的 sets 集合)

Command Parameters Description
ZADD key score member Add the specified member to the Sorted Set value at key or update the score if it already exist.
将member存放到key中,并根据score值的大小进行从小到大的顺序排序.如果member的值已经存在,则会重新根据score的值进行排序
ZREM key member Remove the specified member from the Sorted Set value at key
ZINCRBY key increment member If the member already exists increment its score by increment, otherwise add the member setting increment as score
ZRANK key member Return the rank (or index) or member in the sorted set at key, with scores being ordered from low to high
ZREVRANK key member Return the rank (or index) or member in the sorted set at key, with scores being ordered from high to low
ZRANGE key start end Return a range of elements from the sorted set at key
ZREVRANGE key start end Return a range of elements from the sorted set at key,exactly like ZRANGE, but the sorted set is ordered in traversed in reverse order, from the greatest to the smallest score
ZRANGEBYSCORE key min max Return all the elements with score >= min and score <= max (a range query) from t he sorted set
ZCOUNT key min max Return the number of elements with score >= min and score <= max in the sorted set
ZCARD key Return the cardinality (number of elements) of the sorted set at key
ZSCORE key element Return the score associated with the specified element of the sorted set at key
ZREMRANGEBYRANK key min max Remove all the elements with rank >= min and rank <= max from the sorted set
ZREMRANGEBYSCORE key min max Remove all the elements with score >= min and score <= max from the sorted set
ZUNIONSTORE/ ZINTERSTORE dstkey N key1 ... keyN WEIGHTS w1 ... wN AGGREGATESUM|MIN|MAX Perform a union or intersection over a number of sorted sets with optional

weight and aggregate

操作 hash 类型的值:

Command Parameters Description
HSET key field value Set the hash field to the specified value. Creates the hash if needed.
HGET key field Retrieve the value of the specified hash field.
HMGET key field1 ... fieldN Get the hash values associated to the specified fields.
HMSET key field1 value1 ... fieldN valueN Set the hash fields to their respective values.
HINCRBY key field integer Increment the integer value of the hash at key on field with integer.
HEXISTS key field Test for existence of a specified field in a hash
HDEL key field Remove the specified field from a hash
HLEN key Return the number of items in a hash.
HKEYS key Return all the fields in a hash.
HVALS key Return all the values in a hash.
HGETALL key Return all the fields and associated values in a hash.

公共操作命令部分:(不受数据类型的影响)

Command Parameters Description
SORT key BY pattern LIMIT start end GET pattern ASC|DESC ALPHA Sort a Set or a List accordingly to the specified parameters
数据持久化控制命令
SAVE - Synchronously save the DB on disk BGSAVE - Asynchronously save the DB on disk
LASTSAVE - Return the UNIX time stamp of the last successfully saving of the dataset on disk
SHUTDOWN - Synchronously save the DB on disk, then shutdown the server
BGREWRITEAOF - Rewrite the append only file in background when it gets too big
远程服务器控制命令
INFO - Provide information and statistics about the server
MONITOR - Dump all the received requests in real time
SLAVEOF - Change the replication settings
CONFIG - Configure a Redis server at runtime

Redis 的 master/slave 复制:

Redis 的 master/slave 数据复制方式可以是一主一从或者是一主多从的方式,Redis 在 master 是非阻塞模式,也就是说在 slave 执行数据同步的时候,master 是可以接受客户端的请求的,并不影响同步数据的一致性,然而在 slave 端是阻塞模式的,slave 在同步 master 数据时,并不能够响应客户端的查询.
Redis 的 master/slave 模式下,master 提供数据读写服务,而 slave 只提供读服.

Redis 的 master/slave 的配置方式是在 slave 主机的 Redis 目录下的 redis.conf 配置文件中添加:

slaveof master_ip master_port

例如:

我们配置我们的 slave 为:redis-slave.conf

daemonize yes
pidfile redis-slave.pid
port 6380
timeout 300
loglevel verbose
logfile stdout
databases 16
save 900 1
save 300 10
save 60 10000
rdbcompression yes
dbfilename dump-slave.rdb
dir /home/falcon/redis-2.0.0/
slaveof 127.0.0.1 6379
appendonly no
appendfsync everysec
vm-enabled no
vm-swap-file logs/redis-slave.swap
vm-max-memory 0
vm-page-size 32
vm-pages 134217728
vm-max-threads 4
glueoutputbuf yes
hash-max-zipmap-entries 64
hash-max-zipmap-value 512
activerehashing yes

启动 slave:

[falcon@www ~/redis-2.0.0]$ ./redis-server redis-slave.conf

查看状态信息:

[falcon@www ~/redis-2.0.0]$ ./redis-cli -p 6380 info
redis_version:1.3.17
redis_git_sha1:00000000
redis_git_dirty:0
arch_bits:32
multiplexing_api:epoll
process_id:10772
uptime_in_seconds:249
uptime_in_days:0
connected_clients:2
connected_slaves:0
blocked_client s:0
used_memory:1756868
used_memory_human:1.68M
changes_since_last_save:0
bgsave_in_progress:0
last_save_time:1281654285
bgrewriteaof_in_progress:0
total_connections_received:13
total_commands_processed:9
expired_keys:0
hash_max_zipmap_entries:64
hash_max_zipmap_value:512
pubsub_channels:0
pubsub_patterns:0
vm_enabled:0
role:slave
master_host:127.0.0.1
master_port:6379
master_link_status:up
master_last_io_seconds_ago:248
db0:keys=23,expires=0

[falcon@www ~/redis-2.0.0]$ ./redis-cli -p 6379 info
redis_version:1.3.17
redis_git_sha1:00000000
redis_git_dirty:0
arch_bits:32
multiplexing_api:epoll
process_id:7663
uptime_in_seconds:16787
uptime_in_days:0
connected_clients:1
connected_slaves:1
blocked_client s:0
used_memory:1757232
used_memory_human:1.68M
changes_since_last_save:0
bgsave_in_progress:0
last_save_time:1281654286
bgrewriteaof_in_progress:0
total_connections_received:835
total_commands_processed:55953
expired_keys:1
hash_max_zipmap_entries:64
hash_max_zipmap_value:512
pubsub_channels:0
pubsub_patterns:0
vm_enabled:0
role:master
db0:keys=23,expires=0

解释:

1、 红色标注为 master/slave 端口和运行模式
2、 蓝色标注为 master/slave 数据是否同步,目前显示为 keys 23 个,0 个过期.

扩展思维:

Redis 可以做一主一从,也可以做一主多从,更可以做一主一从,在从下面挂从,大家可以根据需求做这样的试验!
Redis命令大全:http://redis.io/commands

redis支持管道技术:http://www.baidu.com/s?bs=edis+%B9%DC%B5%C0&f=8&wd=redis+%B9%DC%B5%C0&inputT=280

One thought on “redis入门教程

  1. Pingback: Redis作者谈Redis应用场景 | OneCoder

Leave a Reply

Your email address will not be published.