redis入門(一)

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、帶權重的消息隊列

一盹沈、redis 入門(一)

二、redis 入門(二)

三吃谣、手寫redis客戶端

四乞封、redis 讀寫分離、高可用

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末岗憋,一起剝皮案震驚了整個濱河市肃晚,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌仔戈,老刑警劉巖关串,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異监徘,居然都是意外死亡晋修,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門凰盔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來墓卦,“玉大人,你說我怎么就攤上這事户敬÷浼簦” “怎么了?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵尿庐,是天一觀的道長忠怖。 經常有香客問我,道長抄瑟,這世上最難降的妖魔是什么凡泣? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮锐借,結果婚禮上问麸,老公的妹妹穿的比我還像新娘。我一直安慰自己钞翔,他們只是感情好严卖,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著布轿,像睡著了一般哮笆。 火紅的嫁衣襯著肌膚如雪来颤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天稠肘,我揣著相機與錄音福铅,去河邊找鬼生宛。 笑死甩挫,一個胖子當著我的面吹牛,可吹牛的內容都是我干的宵距。 我是一名探鬼主播环揽,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼略荡,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了歉胶?” 一聲冷哼從身側響起汛兜,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎通今,沒想到半個月后粥谬,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡辫塌,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年漏策,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片璃氢。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡哟玷,死狀恐怖,靈堂內的尸體忽然破棺而出一也,到底是詐尸還是另有隱情巢寡,我是刑警寧澤,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布椰苟,位于F島的核電站抑月,受9級特大地震影響,放射性物質發(fā)生泄漏舆蝴。R本人自食惡果不足惜谦絮,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望洁仗。 院中可真熱鬧层皱,春花似錦、人聲如沸赠潦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽她奥。三九已至瓮增,卻和暖如春怎棱,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背绷跑。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工拳恋, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人砸捏。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓谬运,卻偏偏與公主長得像,于是被迫代替她去往敵國和親垦藏。 傳聞我的和親對象是個殘疾皇子吩谦,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內容

  • Redis 是一個鍵值對數(shù)據(jù)庫(key-value DB),數(shù)據(jù)庫的值可以是字符串膝藕、集合、列表等多種類型的對象咐扭,而...
    吳昂_ff2d閱讀 3,248評論 0 5
  • redis入門指南第二版讀書筆記 作者:李子驊 讀者:張劍 Redis是以高性能著稱的內存數(shù)據(jù)庫芭挽,通常用來做緩存服...
    cajan2閱讀 778評論 0 3
  • 1.key的數(shù)據(jù)類型 1.1 key的數(shù)據(jù)結構 Redis key值是二進制安全的,這意味著可以用任何二進制序列作...
    阿貍404閱讀 422評論 0 1
  • [TOC] redis是什么 官方解釋:redis 是一個開源的蝗肪,內存中的K-V數(shù)據(jù)結構存儲系統(tǒng)袜爪,它可以用作數(shù)據(jù)庫...
    0x70e8閱讀 465評論 0 1
  • 今夜,我一口氣做了近兩個小時的作業(yè)薛闪,我困倦地丟開了筆辛馆,伸了個懶腰,打了個哈欠豁延。夜真靜瓣几荨!奶奶早已進入夢鄉(xiāng)了...
    杏聯(lián)梁文靜閱讀 340評論 1 0