redis 簡介
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.
Redis是一個開源的使用ANSI C語言編寫、遵守BSD協(xié)議灭忠、支持網絡蜀细、可基于內存亦可持久化的日志型在岂、Key-Value數(shù)據(jù)庫谒兄,并提供多種語言的API衣赶。
它通常被稱為數(shù)據(jù)結構服務器伍茄,因為值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等類型淹朋。
redis 能做什么
眾多語言都支持Redis偏塞,因為Redis交換數(shù)據(jù)快唱蒸,在服務器中常用來存儲一些需要頻繁調取的數(shù)據(jù),節(jié)省內存開銷灸叼,也極大的提升了速度神汹。
將一些熱點數(shù)據(jù)存儲到Redis中,要用的時候怜姿,直接從內存取慎冤,極大的提高了速度和節(jié)約了服務器的開銷。
1沧卢、會話緩存(最常用)
2蚁堤、消息隊列(支付)
3、活動排行榜或計數(shù)
4但狭、發(fā)布披诗,訂閱消息(消息通知)
5、商品列表立磁,評論列表
redis 安裝(mac or Base Linux ,window 可以直接下載包)
- 下載安裝(編譯)
# 下載
$ wget http://download.redis.io/releases/redis-5.0.8.tar.gz
# 解壓
$ tar xzf redis-5.0.8.tar.gz
#進入解壓包
$ cd redis-5.0.8
#編譯
$ make
# 啟動服務器
$ src/redis-server
#啟動客戶端
$ src/redis-cli
- server命令說明
martain@martaindeMBP redis % src/redis-server -h
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 --replicaof 127.0.0.1 8888
./redis-server /etc/myredis.conf --loglevel verbose
Sentinel mode:
./redis-server /etc/sentinel.conf --sentinel
martain@martaindeMBP redis %
- 選擇配置文件執(zhí)行server
執(zhí)行步驟
1.復制配置文件一份
2.找到port呈队,將port的值修改為6380
3.使用命令redis-server conf-path 啟動服務
- client命令說明
martain@martaindeMBP redis % src/redis-cli -h
redis-cli 5.0.8
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.
You can also use the REDISCLI_AUTH environment
variable to pass this password more safely
(if both are used, this argument takes predecence).
-u <uri> Server URI.
-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.
If you use this mode in an interactive session it runs
forever displaying real-time stats. Otherwise if --raw or
--csv is specified, or if you redirect the output to a non
TTY, it samples the latency for 1 second (you can use
-i to change the interval), then produces a single output
and exits.
--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.
--replica Simulate a replica 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 keys with many elements (complexity).
--memkeys Sample Redis keys looking for keys consuming a lot of memory.
--memkeys-samples <n> Sample Redis keys looking for keys consuming a lot of memory.
And define number of key elements to sample
--hotkeys Sample Redis keys looking for hot keys.
only works when maxmemory-policy is *lfu.
--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>.
--ldb Used with --eval enable the Redis Lua debugger.
--ldb-sync-mode Like --ldb but uses the synchronous Lua debugger, in
this mode the server is blocked and script changes are
not rolled back from the server memory.
--cluster <command> [args...] [opts...]
Cluster Manager command and arguments (see below).
--verbose Verbose mode.
--no-auth-warning Don't show warning message when using password on command
line interface.
--help Output this help and exit.
--version Output version and exit.
Cluster Manager Commands:
Use --cluster help to list all available cluster manager commands.
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
and settings.
- client 連接服務器
# 默認端口是6379 -p可以指定端口
martain@martaindeMBP redis % src/redis-cli -p 6380
127.0.0.1:6380>
redis 數(shù)據(jù)類型及基本操作
Redis一共支持五種數(shù)據(jù)類型:String(字符串)、hash(哈希)唱歧、list(列表)宪摧、set(集合)和zset(sorted set有序集合)
String(字符串):Redis最基本的數(shù)據(jù)類型粒竖,一個鍵對應一個值,一個鍵值最大存儲512MB
Hash(哈希):hash是一個鍵值對的集合几于,是一個String類型的field和value的映射表蕊苗,適合用于存儲對象
List(列表):是redis的簡單的字符串列表,按插入順序排序
Set(集合):是String字符串類型的無序集合沿彭,也不可重復
ZSet(sorted set 有序集合)是String類型的有序集合朽砰,也不可重復。有序集合中的每個元素都需要指定一個分數(shù)喉刘,根據(jù)分數(shù)對元素進行升序排序瞧柔。
- 字符串
127.0.0.1:6380> set param "redis"
OK
127.0.0.1:6380> get param
"redis"
127.0.0.1:6380>
- Hash
Redis hash 是一個鍵值(key=>value)對集合。
Redis hash 是一個 string 類型的 field 和 value 的映射表睦裳,hash 特別適合用于存儲對象造锅。
127.0.0.1:6380> HMSET user name "martain" age 18
OK
127.0.0.1:6380> HGET user name
"martain"
127.0.0.1:6380> HGET user age
"18"
127.0.0.1:6380>
實例中我們使用了 Redis HMSET, HGET 命令,HMSET 設置了兩個 field=>value 對, HGET 獲取對應 field 對應的 value推沸。每個 hash 可以存儲 232 -1 鍵值對(40多億)备绽。
- List(列表
Redis 列表是簡單的字符串列表,按照插入順序排序鬓催。你可以添加一個元素到列表的頭部(左邊)或者尾部(右邊)肺素。
127.0.0.1:6380> LPUSH mylist "martain01"
(integer) 1
127.0.0.1:6380> LPUSH mylist "martain02"
(integer) 2
127.0.0.1:6380> LPUSH mylist "martain03"
(integer) 3
127.0.0.1:6380> LRANGE mylist 0 10
1) "martain03"
2) "martain02"
3) "martain01"
127.0.0.1:6380>
列表最多可存儲 232 - 1 元素 (4294967295, 每個列表可存儲40多億)。
- Set(集合)
- sadd
Redis 的 Set 是 string 類型的無序集合宇驾。集合是通過哈希表實現(xiàn)的倍靡,所以添加,刪除课舍,查找的復雜度都是 O(1)塌西。
127.0.0.1:6380> SADD myset mongo
(integer) 1
127.0.0.1:6380> SADD myset redis
(integer) 1
127.0.0.1:6380> SADD myset mysql
(integer) 1
127.0.0.1:6380> SADD myset mysql
(integer) 0
127.0.0.1:6380> SMEMBERS myset
1) "redis"
2) "mongo"
3) "mysql"
注意:以上實例中 mysql 添加了兩次,但根據(jù)集合內元素的唯一性筝尾,第二次插入的元素將被忽略捡需。集合中最大的成員數(shù)為 232 - 1(4294967295, 每個集合可存儲40多億個成員)。
- zset(sorted set:有序集合)
Redis zset 和 set 一樣也是string類型元素的集合,且不允許重復的成員筹淫。
不同的是每個元素都會關聯(lián)一個double類型的分數(shù)站辉。redis正是通過分數(shù)來為集合中的成員進行從小到大的排序。zset的成員是唯一的,但分數(shù)(score)卻可以重復损姜。
127.0.0.1:6380> ZADD mylan java
(error) ERR wrong number of arguments for 'zadd' command
127.0.0.1:6380> ZADD mylan 0 java
(integer) 1
127.0.0.1:6380> ZADD mylan 0 php
(integer) 1
127.0.0.1:6380> ZADD mylan 0 python
(integer) 1
127.0.0.1:6380> ZADD mylan 0 nodejs
(integer) 1
127.0.0.1:6380> ZRANGEBYSCORE mylan 0 10000
1) "java"
2) "nodejs"
3) "php"
4) "python"
127.0.0.1:6380>
類型 | 簡介 | 特性 | 場景 |
---|---|---|---|
String | 二進制安全 | 可以包含任何數(shù)據(jù),比如jpg圖片或者序列化的對象,一個鍵最大能存儲512M | --- |
Hash | 鍵值對集合,即編程語言中的Map類型 | 適合存儲對象,并且可以像數(shù)據(jù)庫中update一個屬性一樣只修改某一項屬性值(Memcached中需要取出整個字符串反序列化成對象修改完再序列化存回去) | 存儲饰剥、讀取、修改用戶屬性 |
List | 鏈表(雙向鏈表) | 增刪快,提供了操作某一段元素的API | 1,最新消息排行等功能(比如朋友圈的時間線) 2,消息隊列 |
Set | 哈希表實現(xiàn),元素不重復 | 1摧阅、添加汰蓉、刪除,查找的復雜度都是O(1) 2、為集合提供了求交集棒卷、并集顾孽、差集等操作 | 1祝钢、共同好友 2、利用唯一性,統(tǒng)計訪問網站的所有獨立ip 3若厚、好友推薦時,根據(jù)tag求交集,大于某個閾值就可以推薦 |
Sorted Set | 將Set中的元素增加一個權重參數(shù)score,元素按score有序排列 | 數(shù)據(jù)插入集合時,已經進行天然排序 | 1太颤、排行榜 2、帶權重的消息隊列 |