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é)議、支持網(wǎng)絡、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。
它通常被稱為數(shù)據(jù)結(jié)構(gòu)服務器,因為值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等類型。

redis 能做什么

眾多語言都支持Redis,因為Redis交換數(shù)據(jù)快,在服務器中常用來存儲一些需要頻繁調(diào)取的數(shù)據(jù),節(jié)省內(nèi)存開銷,也極大的提升了速度。
將一些熱點數(shù)據(jù)存儲到Redis中,要用的時候,直接從內(nèi)存取,極大的提高了速度和節(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ù)集合內(nèi)元素的唯一性,第二次插入的元素將被忽略。集合中最大的成員數(shù)為 232 - 1(4294967295, 每個集合可存儲40多億個成員)。

  • zset(sorted set:有序集合)

Redis zset 和 set 一樣也是string類型元素的集合,且不允許重復的成員。
不同的是每個元素都會關(guān)聯(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)計訪問網(wǎng)站的所有獨立ip 3、好友推薦時,根據(jù)tag求交集,大于某個閾值就可以推薦
Sorted Set 將Set中的元素增加一個權(quán)重參數(shù)score,元素按score有序排列 數(shù)據(jù)插入集合時,已經(jīng)進行天然排序 1、排行榜 2、帶權(quán)重的消息隊列

一、redis 入門(一)

二、redis 入門(二)

三、手寫redis客戶端

四、redis 讀寫分離、高可用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • Redis 是一個鍵值對數(shù)據(jù)庫(key-value DB),數(shù)據(jù)庫的值可以是字符串、集合、列表等多種類型的對象,而...
    吳昂_ff2d閱讀 3,750評論 0 5
  • redis入門指南第二版讀書筆記 作者:李子驊 讀者:張劍 Redis是以高性能著稱的內(nèi)存數(shù)據(jù)庫,通常用來做緩存服...
    cajan2閱讀 823評論 0 3
  • 1.key的數(shù)據(jù)類型 1.1 key的數(shù)據(jù)結(jié)構(gòu) Redis key值是二進制安全的,這意味著可以用任何二進制序列作...
    阿貍404閱讀 488評論 0 1
  • [TOC] redis是什么 官方解釋:redis 是一個開源的,內(nèi)存中的K-V數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),它可以用作數(shù)據(jù)庫...
    0x70e8閱讀 513評論 0 1
  • 今夜,我一口氣做了近兩個小時的作業(yè),我困倦地丟開了筆,伸了個懶腰,打了個哈欠。夜真靜?。∧棠淘缫堰M入夢鄉(xiāng)了...
    杏聯(lián)梁文靜閱讀 383評論 1 0

友情鏈接更多精彩內(nèi)容