zoukankan      html  css  js  c++  java
  • 第1讲 Redis部署与基本操作

    目录
    
    一、简介
    二、安装
        1、默认安装位置
        2、指定安装位置
        3、安装的可执行文件的作用
    三、启动与关闭
    四、配置文件
    五、Redis的数据类型
        1. 共计5种类型
        2. String(子串类型)
        3. hashs类型
        4. list类型(双向链表结构)
        5. sets类型和操作
    

    一、简介

    redis是一个key-value存储系统。
    和Memcached类似,它支持存储的value类型相对更多,
    包括string(字符串)、list(链表)、set(集合)和zset(有序集合)。
    这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。

    在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。
    区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

    Redis 是一个高性能的key-value数据库。
    redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部 分场合可以对关系数据库起到很好的补充作用。
    它提供了Python,Ruby,Erlang,PHP客户端,使用很方便。

    • Memcache
      内存缓存服务,缓存数据保存在内存中,一旦断电重启,数据将丢失
    • mongoDB
      开源免费的NOSQL 数据库,提供数据持久化服务,以文档的形式提供数据组织方式,而不是表
    • Redis
      开源免费的 NOSQL数据库,提供数据持久化服务,即能实现内存缓存服务,也能提供数据结构服务
      取代MySQL 自建索引
      用来弥补关系型数据的不足

    二、安装

    1、默认安装位置

    [root@localhost ~]#
    wget http://download.redis.io/releases/redis-2.8.6.tar.gz
    [root@localhost ~]#tar xzf redis-2.8.6.tar.gz
    [root@localhost ~]#cd redis-2.8.6
    [root@localhost ~]#make
    #不指定安装位置,则会把redis的可执行文件安装到  redis-2.8.6/src/目录下
    

    2、指定安装位置

    [root@localhost ~]#tar xzf redis-2.8.6.tar.gz
    [root@localhost ~]# cd redis-2.8.6
    [root@localhost ~]# make
    [root@localhost ~]# make PREFIX=/usr/local/redis install
    #指定安装位置,如果没有指定安装位置PREFIX=/usr/local/redis,则make install会把redis安装到/usr/local/bin/目录下
    [root@localhost~]# mkdir/usr/local/redis/etc
    [root@localhost~]#cp /root/redis-2.8.6/redis.conf /usr/local/redis/etc/
    

    3、安装的可执行文件的作用

    redis-server	服务器端
    redis-cli	客户端
    redis-benchmark	调试
    redis-check-dump	数据导出
    redis-check-aof	数据导入
    

    三、启动与关闭

    1、	启动
    

    路径/redis-server 配置文件

    /usr/local/redis/bin/redis-server/usr/local/redis/etc/redis.conf
    

    注意:需要修改配置文件

    [root@localhostredis]# vi /usr/local/redis/etc/redis.conf
    

    daemonizeno 改为
    daemonize yes #后台启动

    端口 6379

    [root@localhostredis]# /usr/local/redis/bin/redis-cli
    
    #客户端连接
    	-h  IP	:		连接指定的redis服务器
    	-p  6379:		指定redis服务器的端口
    	-a  密码:		使用密码登录
    	-n 数据库号:	指定连接哪个数据库
    
    2、	关闭redis
    
    [root@localhost ~]# /usr/local/redis/bin/redis-cli shutdown
    

    [root@localhost ~]# pkill  -9 redis
    

    四、配置文件

    [root@localhostredis]# vi /usr/local/redis/etc/redis.conf
    #是否以后台进程运行,默认为no,如果需要以后台进程运行则改为yes
    daemonize no
    
    
    #如果以后台进程运行的话,就需要指定pid,你可以在此自定义redis.pid文件的位置。
    pidfile /var/run/redis.pid
    
    
    #接受连接的端口号,如果端口是0则redis将不会监听TCP socket连接
    port 6379
    
    # If you want you can bind a single interface, if the bind option is not
    # specified all the interfaces will listen for incoming connections.
    #
    # bind 127.0.0.1
    
    # Specify the path for the unix socket that will be used to listen for
    # incoming connections. There is no default, so Redis will not listen
    # on a unix socket when not specified.
    #
    # unixsocket /tmp/redis.sock
    # unixsocketperm 755
    
    
    #连接超时时间,单位秒。(0 to disable)?
    timeout 300000000
    
    
    #日志级别,默认是verbose(详细),各种日志级别:
    #debug:很详细的信息,适合开发和测试
    #verbose:包含许多不太有用的信息,但比debug要清爽一些(many rarely useful info, but not a mess like #the debug level)
    #notice:比较适合生产环境
    #warning:警告信息
    loglevel verbose
    
    
    #指定log文件的名字,默认是stdout。stdout会让redis把日志输出到标准输出。但是如果使用stdout而又以后台进#程的方式运行redis,则日志会输出到/dev/null
    logfilestdout
    
    
    #'syslog-enabled'设置为yes会把日志输出到系统日志,默认是no
    # syslog-enabled no
    
    
    #指定syslog的标示符,如果'syslog-enabled'是no,则这个选项无效。
    # syslog-identredis
    
    
    #指定syslog 设备(facility), 必须是USER或者LOCAL0到LOCAL7.
    # syslog-facility local0
    
    
    #设置数据库数目。默认的数据库是DB 0。可以通过SELECT <dbid>来选择一个数据库,dbid是[0,'databases'-1]的数字
    databases 16
    
    ################## 快照#################################
    #
    # 硬盘上保存数据:
    #
    #   save <seconds><changes>
    #
    #   <seconds>和<changes>都满足时就会触发数据保存动作。
    #   
    #
    #   以下面的例子来说明:
    #   过了900秒并且有1个key发生了改变 就会触发save动作
    #   过了300秒并且有10个key发生了改变 就会触发save动作
    #   过了60秒并且至少有10000个key发生了改变 也会触发save动作
    #
    #   注意:如果你不想让redis自动保存数据,那就把下面的配置注释掉!
    
    save 900 1
    save 300 10
    save 60 10000
    
    
    #存储数据时是否压缩数据。默认是yes。
    rdbcompression yes
    
    # 保存dump数据的文件名
    dbfilenamedump.rdb
    
    # 工作目录.
    #
    # 数据会被持久化到这个目录下的‘dbfilename’指定的文件中。
    # 
    # 
    # 注意,这里指定的必须是目录而不能是文件。
    dir ./
    
    ######## REPLICATION(复制,冗余)#################################
    
    # Master-Slave replication. 使用slaveof把一个 Redis 实例设置成为另一个Redis server的从库(热备). 注意: #配置只对当前slave有效。
    # 因此可以把某个slave配置成使用不同的时间间隔来保存数据或者监听其他端口等等。
    #命令格式:
    # slaveof<masterip><masterport>
    
    
    #如果master有密码保护,则在slave与master进行数据同步之前需要进行密码校验,否则master会拒绝slave的请#求。
    #
    # masterauth<master-password>
    
    #当slave丢失与master的连接时,或者slave仍然在于master进行数据同步时(还没有与master保持一致),#slave可以有两种方式来响应客户端请求:
    #
    # 1) 如果 slave-serve-stale-data 设置成 'yes' (the default) slave会仍然响应客户端请求,此时可能会有问题。
    #
    # 2) 如果 slave-serve-stale data设置成  'no'  slave会返回"SYNC with master in progress"这样的错误信息。 但 INFO 和SLAVEOF命令除外。
    #
    slave-serve-stale-data yes
    
    ############### 安全 ###################################
    
    # 需要客户端在执行任何命令之前指定 AUTH <PASSWORD>
    #
    # requirepassfoobared
    
    # 命令重命名.
    #
    #
    # 例如:
    #
    # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
    #
    # 同样可以通过把一个命令重命名为空串来彻底kill掉这个命令,比如:
    #
    # rename-command CONFIG ""
    
    #################### 限制 ####################################
    
    # 设置最大连接数. 默认没有限制,  '0' 意味着不限制.
    #
    # maxclients 128
    
    
    #最大可使用内存。如果超过,Redis会试图删除EXPIRE集合中的keys,具体做法是:Redis会试图释放即将过期的#keys,而保护还有很长生命周期的keys。
    #
    #如果这样还不行,Redis就会报错,但像GET之类的查询请求还是会得到响应。
    #
    #警告:如果你想把Redis视为一个真正的DB的话,那不要设置<maxmemory>,只有你只想把Redis作为cache或者
    #有状态的server('state' server)时才需要设置。
    #
    # maxmemory<bytes>
    
    #内存清理策略:如果达到了maxmemory,你可以采取如下动作:
    # 
    # volatile-lru -> 使用LRU算法来删除过期的set
    # allkeys-lru -> 删除任何遵循LRU算法的key
    # volatile-random ->随机地删除过期set中的key
    # allkeys->random -> 随机地删除一个key
    # volatile-ttl -> 删除最近即将过期的key(the nearest expire time (minor TTL))
    # noeviction -> 根本不过期,写操作直接报错
    # 
    #
    # 默认策略:
    #
    # maxmemory-policy volatile-lru
    
    # 对于处理redis内存来说,LRU和minor TTL算法不是精确的,而是近似的(估计的)算法。所以我们会检查某些样本#来达到内存检查的目的。默认的样本数是3,你可以修改它。
    #
    # maxmemory-samples 3
    
    ################# APPEND ONLY MODE ###############################
    
    #默认情况下,Redis会异步的把数据保存到硬盘。如果你的应用场景允许因为系统崩溃等极端情况而导致最新数据丢失#的话,那这种做法已经很ok了。否则你应该打开‘append only’模式,开启这种模式后,Redis会在#appendonly.aof文件中添加每一个写操作,这个文件会在Redis启动时被读取来在内存中重新构建数据集。
    #
    #注意:如果你需要,你可以同时开启‘append only’模式和异步dumps模式(你需要注释掉上面的‘save’表达式来禁#止dumps),这种情况下,Redis重建数据集时会优先使用appendonly.aof而忽略dump.rdb
    #
    appendonly no
    
    #  append only 文件名 (默认: "appendonly.aof")
    # appendfilenameappendonly.aof
    
    # 调用fsync()函数通知操作系统立刻向硬盘写数据
    #
    # Redis支持3中模式:
    #
    # no:不fsync, 只是通知OS可以flush数据了,具体是否flush取决于OS.性能更好.
    # always: 每次写入append only 日志文件后都会fsync . 性能差,但很安全.
    # everysec: 没间隔1秒进行一次fsync. 折中.
    #
    # 默认是 "everysec"
    # appendfsync always
    appendfsynceverysec
    # appendfsync no
    
    # 当AOF fsync策略被设置为always或者everysec并且后台保存进程(saving process)正在执行大量I/O操作时
    # Redis可能会在fsync()调用上阻塞过长时间
    #
    no-appendfsync-on-rewrite no
    
    # append only 文件的自动重写
    # 当AOF 日志文件即将增长到指定百分比时,Redis可以通过调用BGREWRITEAOF 来自动重写append only文件。
    # 
    # 它是这么干的:Redis会记住最近一次重写后的AOF 文件size。然后它会把这个size与当前size进行比较,如果当前# size比指定的百分比大,就会触发重写。同样,你需要指定AOF文件被重写的最小size,这对避免虽然百分比达到了# 但是实际上文件size还是很小(这种情况没有必要重写)却导致AOF文件重写的情况很有用。
    #
    #
    # auto-aof-rewrite-percentage 设置为 0 可以关闭AOF重写功能
    
    auto-aof-rewrite-percentage 100
    auto-aof-rewrite-min-size 64mb
    
    ################## SLOW LOG ###################################
    
    # Redis slow log用来记录超过指定执行时间的查询。
    # 
    # 你可以指定两个参数:一个是慢查询的阀值,单位是毫秒;另外一个是slow log的长度,相当于一个队列。
    
    # 负数则关闭slow log,0则会导致每个命令都被记录
    slowlog-log-slower-than 10000
    
    # 不设置会消耗过多内存,所以还是要设置一下。可以使用SLOWLOG RESET命令来回收slow log使用的内存
    slowlog-max-len 1024
    
    ################ 虚拟内存 ###############################
    #使用redis 就别用虚拟内存了,绝对不是一个好主意,加个机器吧,所以这里不翻译啦!!
    
    ### WARNING! Virtual Memory is deprecated in Redis 2.4
    ### The use of Virtual Memory is strongly discouraged.
    
    # Virtual Memory allows Redis to work with datasets bigger than the actual
    # amount of RAM needed to hold the whole dataset in memory.
    # In order to do so very used keys are taken in memory while the other keys
    # are swapped into a swap file, similarly to what operating systems do
    # with memory pages.
    #
    # To enable VM just set 'vm-enabled' to yes, and set the following three
    # VM parameters accordingly to your needs.
    
    vm-enabled no
    # vm-enabled yes
    
    # This is the path of the Redis swap file. As you can guess, swap files
    # can't be shared by different Redis instances, so make sure to use a swap
    # file for every redis process you are running. Redis will complain if the
    # swap file is already in use.
    #
    # The best kind of storage for the Redis swap file (that's accessed at random) 
    # is a Solid State Disk (SSD).
    #
    # *** WARNING *** if you are using a shared hosting the default of putting
    # the swap file under /tmp is not secure. Create a dir with access granted
    # only to Redis user and configure Redis to create the swap file there.
    vm-swap-file /tmp/redis.swap
    
    # vm-max-memory configures the VM to use at max the specified amount of
    # RAM. Everything that deos not fit will be swapped on disk *if* possible, that
    # is, if there is still enough contiguous space in the swap file.
    #
    # With vm-max-memory 0 the system will swap everything it can. Not a good
    # default, just specify the max amount of RAM you can in bytes, but it's
    # better to leave some margin. For instance specify an amount of RAM
    # that's more or less between 60 and 80% of your free RAM.
    vm-max-memory 0
    
    # Redis swap files is split into pages. An object can be saved using multiple
    # contiguous pages, but pages can't be shared between different objects.
    # So if your page is too big, small objects swapped out on disk will waste
    # a lot of space. If you page is too small, there is less space in the swap
    # file (assuming you configured the same number of total swap file pages).
    #
    # If you use a lot of small objects, use a page size of 64 or 32 bytes.
    # If you use a lot of big objects, use a bigger page size.
    # If unsure, use the default :)
    vm-page-size 32
    
    # Number of total memory pages in the swap file.
    # Given that the page table (a bitmap of free/used pages) is taken in memory,
    # every 8 pages on disk will consume 1 byte of RAM.
    #
    # The total swap size is vm-page-size * vm-pages
    #
    # With the default of 32-bytes memory pages and 134217728 pages Redis will
    # use a 4 GB swap file, that will use 16 MB of RAM for the page table.
    #
    # It's better to use the smallest acceptable value for your application,
    # but the default is large in order to work in most conditions.
    vm-pages 134217728
    
    # Max number of VM I/O threads running at the same time.
    # This threads are used to read/write data from/to swap file, since they
    # also encode and decode objects from disk to memory or the reverse, a bigger
    # number of threads can help with big objects even if they can't help with
    # I/O itself as the physical device may not be able to couple with many
    # reads/writes operations at the same time.
    #
    # The special value of 0 turn off threaded I/O and enables the blocking
    # Virtual Memory implementation.
    vm-max-threads 4
    
    ################高级配置###############################
    
    # Hashes are encoded in a special way (much more memory efficient) when they
    # have at max a given numer of elements, and the biggest element does not
    # exceed a given threshold. You can configure this limits with the following
    # configuration directives.
    hash-max-zipmap-entries 512
    hash-max-zipmap-value 64
    
    # Similarly to hashes, small lists are also encoded in a special way in order
    # to save a lot of space. The special representation is only used when
    # you are under the following limits:
    list-max-ziplist-entries 512
    list-max-ziplist-value 64
    
    # Sets have a special encoding in just one case: when a set is composed
    # of just strings that happens to be integers in radix 10 in the range
    # of 64 bit signed integers.
    # The following configuration setting sets the limit in the size of the
    # set in order to use this special memory saving encoding.
    set-max-intset-entries 512
    
    # Similarly to hashes and lists, sorted sets are also specially encoded in
    # order to save a lot of space. This encoding is only used when the length and
    # elements of a sorted set are below the following limits:
    zset-max-ziplist-entries 128
    zset-max-ziplist-value 64
    
    # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in
    # order to help rehashing the main Redis hash table (the one mapping top-level
    # keys to values). The hash table implementation redis uses (see dict.c)
    # performs a lazy rehashing: the more operation you run into an hash table
    # that is rhashing, the more rehashing "steps" are performed, so if the
    # server is idle the rehashing is never complete and some more memory is used
    # by the hash table.
    # 
    # The default is to use this millisecond 10 times every second in order to
    # active rehashing the main dictionaries, freeing memory when possible.
    #
    # If unsure:
    # use "activerehashing no" if you have hard latency requirements and it is
    # not a good thing in your environment that Redis can reply form time to time
    # to queries with 2 milliseconds delay.
    #
    # use "activerehashing yes" if you don't have such hard requirements but
    # want to free memory asap when possible.
    activerehashing yes
    
    ################## INCLUDES ###################################
    
    # Include one or more other config files here.  This is useful if you
    # have a standard template that goes to all redis server but also need
    # to customize a few per-server settings.  Include files can include
    # other files, so use this wisely.
    #
    # include /path/to/local.conf
    # include /path/to/other.conf
    

    五、Redis的数据类型

    1. 共计5种类型

    string(字符串)、hash(哈希表) list(双向队列)、set(集合)和zset(有序集合)
    

    2. String(子串类型)

    String是最简单的类型,一个Key对应一个Value,string类型是二进制安全的。Redis的string可以包含任何数据,比如jpg图片或者序列化的对象。
    

    1)set 键 "值"
    设置一个键和值,键存在则覆盖,返回ok

    127.0.0.1:6379> set name liming
    OK
    

    2)get 键
    获取一个键的值,返回值

    127.0.0.1:6379> get name
    "liming"
    

    3) setnx 键 值
    只有当该键不存在时设置一个键的值,若键已存在则返回0表示失败(防止覆盖),

    127.0.0.1:6379>setnx age 18
    (integer) 1
    127.0.0.1:6379>setnx age 18
    (integer) 0
    

    4) setex 键 [有效时间] 值
    设置一个指定有效期的键和值(单位秒)。不写有效时间则表示永久有效,等价于set

    127.0.0.1:6379>setex movie 30 canglaoshi
    OK
    127.0.0.1:6379>ttl movie				//获取键的有效时间
    (integer) 26
    127.0.0.1:6379>ttl movie
    (integer) 20
    127.0.0.1:6379> get movie
    "canglaoshi"
    127.0.0.1:6379>ttl movie
    (integer) -2
    127.0.0.1:6379> get movie
    (nil)
    

    5)ttl 键
    以秒为单位,返回给定 key 的剩余生存时间
    >当 key 不存在时,返回 -2 。
    当 key 存在但没有设置剩余生存时间时,返回 -1 。
    否则,以秒为单位,返回 key 的剩余生存时间。

    127.0.0.1:6379> ttl name
    (integer) -1
    

    6) setrange 键 位置 子字串
    替换子字符串 (替换长度由子子串长度决定)

    127.0.0.1:6379> set key1 "hello world"
    OK
    127.0.0.1:6379> get key1
    "hello world"
    127.0.0.1:6379>setrange key1 6 liming
    (integer) 12
    127.0.0.1:6379> get key1
    "hello liming"
    	#将key1键对应值的第6个位置开始替换(字符串位置从0开始计算)
    

    7) mset 键1 值1 键2 值2 键3 值3 ....
    批量设置键和值,成功则返回ok

    127.0.0.1:6379>mset name1 lm name2 sc name3 zjj
    OK
    

    8) mget 键1 键2 键3....
    批量获取值

    127.0.0.1:6379>mget name1 name2 name3
    1) "lm"
    2) "sc"
    3) "zjj"
    

    9) msetnx 键1 值1 键2 值2 键3 值3 ....
    批量设置不存在的键和值,成功则返回ok

    10) getset 键 新值
    获取原值,并设置新值

    127.0.0.1:6379> set name "shenchao"
    OK
    127.0.0.1:6379> get name
    "shenchao"
    127.0.0.1:6379>getset name "liming"
    "shenchao"
    127.0.0.1:6379> get name
    "liming"
    

    11) getrange 键 0 4
    获取指定范围的值(获取指定0到4位置上的值,字符串位置从0开始计算)。参考setrange。

    127.0.0.1:6379>getrange key1 0 4
    "hello"
    

    12) incr键
    指定键的值做加1操作,返回加后的结果(只能加数字)。

    127.0.0.1:6379> set age 18
    OK
    127.0.0.1:6379>incr age
    (integer) 19
    127.0.0.1:6379> get age
    "19"
    

    13) incrby 键 m
    //其中m可以是正整数或负整数
    加指定值,键不存在时候会设置键

    127.0.0.1:6379>incrby age 10
    (integer) 29
    127.0.0.1:6379> get age
    "29"
    127.0.0.1:6379>incrby age -5
    (integer) 24
    

    14)decr 键
    指定键的值做减1操作,返回减后的结果。

    127.0.0.1:6379>decr age
    (integer) 23
    127.0.0.1:6379> get age
    "23"
    

    15) decrby 键 n
    //其中n可以是正整数或负整数
    设置某个键减上指定值

    127.0.0.1:6379>decrby age 5
    (integer) 18
    127.0.0.1:6379>decrby age -10
    (integer) 28
    127.0.0.1:6379> get age
    "28"
    

    16)append 键 追加字串
    给指定key的字符串追加value,返回新字符串值的长度

    127.0.0.1:6379> append name1 " have a hot body!"
    (integer) 19
    127.0.0.1:6379> get name1
    "lm have a hot body!"
    

    17) strlen 键名
    strlen求一个键长度

    127.0.0.1:6379>strlen name1
    (integer) 19
    

    18)del命令:删除一个键

    127.0.0.1:6379>del name3
    (integer) 1
    127.0.0.1:6379> get name3
    (nil)
    

    3. hashs类型

    注意:redis中没有表概念,所有的数据都存入键中。
    

    string键类型:所有的值(可以是任何数据类型)都保存在一个键当中,放在一个内存块中

    hashs键类型:所有的值也都保存在一个键当中,只是放在不同的内存块中,每个块称作字段

    1)hset key field value
    设置一个键,在键中保存字段和值

    hset 哈希集(键) 字段 值
    
    127.0.0.1:6379>hset user1 name4 ysm
    (integer) 1
    127.0.0.1:6379> keys *					//查看库中所有的键
    1) "aa"
    2) "name"
    3) "name1"
    4) "user1"
    5) "name2"
    6) "age"
    7) "key1"
    

    2)hsetnx 键 字段 值
    设置一个键中,不存在的字段和值。如果字段存在则报错(成功返回1,失败返回0)

    127.0.0.1:6379>hsetnx user1 name1 lm
    (integer) 1
    127.0.0.1:6379>hsetnx user1 name1 sc
    (integer) 0					//报错
    127.0.0.1:6379>hget user1 name1
    "lm"						//内容没有更新
    

    3)hmset 键 字段1 值1 字段2 值2 …
    在一个键中,批量设置字段

    127.0.0.1:6379>hmset user2 name liming age 36 interest AV-Girl
    OK
    

    4)hget 键 字段
    获取键中的一个指定字段的值

    127.0.0.1:6379>hget user1 name1
    "lm"
    127.0.0.1:6379>hget user2 interest
    "AV-Girl"
    

    5)hmget 键 字段1 [字段2…]
    获取键中一个或多个字段的值

    127.0.0.1:6379>hmget user2 name age interest
    1) "liming"
    2) "36"
    3) "AV-Girl"
    

    6) hexists :判断指定的字段是否存在于键中

    hexists 键 字段
    

    例如:

    127.0.0.1:6379> HEXISTS user2 age
    (integer) 1							//存在
    127.0.0.1:6379> HEXISTS user1 age	
    (integer) 0							//不存在
    

    7) hlen :获取键中的字段数量

    hlen 键
    
    127.0.0.1:6379>hlen user2
    (integer) 3							//user2键中有3个字段
    

    8)hkeys :获取键中的所有字段名

    127.0.0.1:6379>hkeys user2
    1) "name"
    2) "age"
    3) "interest"
    

    9)hvals:获取键中所有字段的值

    127.0.0.1:6379>hvals user2
    1) "liming"
    2) "36"
    3) "AV-Girl"
    

    10)hgetall :获取键中的所有字段和值

    127.0.0.1:6379>hgetall user2
    1) "name"
    2) "liming"
    3) "age"
    4) "36"
    5) "interest"
    6) "AV-Girl"
    

    11)hincrby:将键中指定字段的值,增加指定的数字

    127.0.0.1:6379>hincrby user2 age 5
    (integer) 41
    
    127.0.0.1:6379> HINCRBY user2 name 5
    (error) ERR hash value is not an integer	//值不是数字的字段,不能加数字
    

    12)hdel 键 字段1 字段2
    删除键中的一个或多个字段

    127.0.0.1:6379>hdel user2 age interest
    (integer) 2
    127.0.0.1:6379>hkeys user2
    1) "name"
    	//删除一个键,还是要使用del命令
    

    4. list类型(双向链表结构)

    List是一个链表结构,主要功能是push、pop、获取一个范围的所有值等等,操作中key理解为链表的名字。Redis的list类型其实就是一个每个子元素都是string类型的双向链表。

    1)lpush 键 值1 [值2…]
    从队列左边向队列写入一个或多个值(认为队列的左面为队列头,右边为队列尾)

    127.0.0.1:6379>lpush list1 1
    (integer) 1
    127.0.0.1:6379>lpush list1 2
    (integer) 2
    127.0.0.1:6379>lpush list1 3
    (integer) 3
    127.0.0.1:6379>lpush list1 4
    (integer) 4
    
    127.0.0.1:6379>lpush list2 one two three four
    (integer) 4
    

    2)lrange 键 起始下标 终止下标
    从队列中获取指定的返回值(从队列左边向右获取)

    下标:0代表队列中第一个元素,1代表第二个元素,依次类推
    	-1代表队列中最后一个元素,-2代表倒数第二个元素
    
    127.0.0.1:6379> LRANGE list1 0 -1
    1) "4"		//4是从左面写入队列的最后一个值,所以在队列的开头
    2) "3"
    3) "2"
    4) "1"		//1是从左面写入队列的第一个值,所以直接放到了队列尾。
    			
    127.0.0.1:6379> LRANGE list2 0 -1
    1) "four"
    2) "three"
    3) "two"
    4) "one"
    
    127.0.0.1:6379> LRANGE list1 0 1
    1) "4"
    2) "3"
    
    127.0.0.1:6379> LRANGE list2 -4 3
    1) "four"		//-4代表从队列右边数第四个元素
    2) "three"
    3) "two"
    4) "one"		//3代表从队列左边数第四个元素
    

    3)rpush键 值1 [值2…]
    从队列右边向队列写入一个或多个值

    127.0.0.1:6379> RPUSH list3 1 2 3 4
    (integer) 4
    127.0.0.1:6379> LRANGE list3 0 -1
    1) "1"		//从队列右边向队列写入值,第一个值就会写到队列的开头
    2) "2"
    3) "3"
    4) "4"
    

    4)linsert 键 before|after 原值 新值
    在队列中指定元素之前或之后插入新值

    127.0.0.1:6379> LINSERT list3 before 3 hello
    (integer) 5
    127.0.0.1:6379> LRANGE list3 0 -1
    1) "1"
    2) "2"
    3) "hello"
    4) "3"
    5) "4"
    

    5)lset 键 下标 新值
    给队列中指定元素设定新值

    127.0.0.1:6379>lset list3 2 "5"
    OK
    127.0.0.1:6379> LRANGE list3 0 -1
    1) "1"
    2) "2"
    3) "5"
    4) "3"
    5) "4"
    

    6)lrem 键 n 指定值

    从队列中删除n个值为“指定值”的元素
    n > 0 	从队列头向尾删除n个元素
    n < 0 	从队列尾向头删除n个元素
    n = 0	删除所有值为“指定值”的元素
    
    127.0.0.1:6379>rpush list4 hello 1 hello 2 hello 3 hello
    (integer) 7
    127.0.0.1:6379>lrange list4 0 -1
    1) "hello"
    2) "1"
    3) "hello"
    4) "2"
    5) "hello"
    6) "3"
    7) "hello"
    127.0.0.1:6379>lrem list4 -2 hello			//删除后两个hello
    (integer) 2
    127.0.0.1:6379>lrange list4 0 -1
    1) "hello"
    2) "1"
    3) "hello"
    4) "2"
    5) "3"
    127.0.0.1:6379>lrem list4 0 hello			//删除所有hello
    (integer) 2
    127.0.0.1:6379>lrange list4 0 -1
    1) "1"
    2) "2"
    3) "3"
    

    7)ltrim 键 起始下标 结束下标
    修剪队列,让队列只保留指定指定范围内的元素

    127.0.0.1:6379> RPUSH list5 1 2 3 4
    (integer) 4
    127.0.0.1:6379>ltrim list5 1 2
    OK
    127.0.0.1:6379>lrange list5 0 -1
    1) "2"
    2) "3"
    

    8)lpop 键
    从指定的队列左面移除一个值

    127.0.0.1:6379>lrange list1 0 -1
    1) "4"
    2) "3"
    3) "2"
    4) "1"
    127.0.0.1:6379>lpop list1
    "4"
    127.0.0.1:6379>lrange list1 0 -1
    1) "3"
    2) "2"
    3) "1"
    

    9)rpop 键
    从指定队列的右边移除一个值

    127.0.0.1:6379>lrange list1 0 -1
    1) "3"
    2) "2"
    3) "1"
    127.0.0.1:6379>rpop list1
    "1"
    127.0.0.1:6379>lrange list1 0 -1
    1) "3"
    2) "2"
    

    10)rpoplpush 源队列 目标队列
    移除源队列的最后一个元素,并把该元素写入目标队列

    127.0.0.1:6379>lrange list1 0 -1
    1) "3"
    2) "2"
    127.0.0.1:6379>lrange list5 0 -1
    1) "2"
    2) "3"
    127.0.0.1:6379> RPOPLPUSH list1 list5
    "2"
    127.0.0.1:6379>lrange list1 0 -1
    1) "3"
    127.0.0.1:6379>lrange list5 0 -1
    1) "2"
    2) "2"
    3) "3"
    

    11)lindex 键 下标
    获取队列中指定下标元素的值

    127.0.0.1:6379>lrange list2 0 -1
    1) "four"
    2) "three"
    3) "two"
    4) "one"
    127.0.0.1:6379>lindex list2 1 
    "three"
    127.0.0.1:6379>lindex list2 3
    "one"
    

    12)llen 键
    获得队列的长度

    127.0.0.1:6379>llen list2
    (integer) 4
    

    5. sets类型和操作

    Set是集合,它是string类型的无序集合。对集合我们可以取并集、交集、差集。通过这些操作我们可以实现社交网站中的好友推荐和blog的tag功能。

    1) sadd 键 值1[值2…]
    添加一个或多个元素到集合中

    127.0.0.1:6379>sadd mset1 1
    (integer) 1
    127.0.0.1:6379>sadd mset1 2 3 4
    (integer) 3
    

    2) smembers 键
    获取集合里面所有的元素

    127.0.0.1:6379>smembers mset1
    1) "1"
    2) "2"
    3) "3"
    4) "4"
    

    3) srem 键 值1[值2…]
    从集合中删除指定的一个或多个元素

    127.0.0.1:6379>srem mset1 3 4
    (integer) 2
    127.0.0.1:6379>smembers mset1
    1) "1"
    2) "2"
    
    	(删除键,依然使用“del 键” 命令)
    

    4) spop 键
    随机从集合中删除一个元素,并返回

    127.0.0.1:6379>sadd mset2 4 5 6 7 8
    (integer) 5
    127.0.0.1:6379>spop mset2
    "4"
    127.0.0.1:6379>spop mset2
    "5"
    127.0.0.1:6379>spop mset2
    "8"
    127.0.0.1:6379>smembers mset2
    1) "6"
    2) "7"
    

    5) srandmember 键 值
    随机返回集合中一个元素,但不删除

    127.0.0.1:6379>sadd mset3 4 5 6 7 8
    (integer) 5
    127.0.0.1:6379>srandmember mset3
    "5"
    127.0.0.1:6379>srandmember mset3
    "5"
    127.0.0.1:6379>srandmember mset3
    "4"
    

    6) scard 键
    获取集合里面元素个数

    127.0.0.1:6379>scard mset1
    (integer) 2
    

    7) sismember 键 值
    确定一个指定的值是否是集合中的元素

    127.0.0.1:6379>smembers mset1
    1) "1"
    2) "2"
    127.0.0.1:6379>sismember mset1 3
    (integer) 0
    127.0.0.1:6379>sismember mset1 1
    (integer) 1
    

    8) sdiff 集合1 集合2
    返回集合1与集合2的差集。以集合1为主

    127.0.0.1:6379>sadd mset4 1 2 3
    (integer) 3
    127.0.0.1:6379>sadd mset5 2 3 4
    (integer) 3
    127.0.0.1:6379>sdiff mset4 mset5
    1) "1"
    

    9) sdiffstore 新集合 集合1 集合2
    返回集合1和集合2的差集,并把结果存入新集合

    127.0.0.1:6379>sadd mset4 1 2 3
    (integer) 3
    127.0.0.1:6379>sadd mset5 2 3 4
    (integer) 3
    127.0.0.1:6379>sdiffstore mset6 mset5 mset4
    (integer) 1				//返回值为1 ,证明成功
    127.0.0.1:6379>smembers mset6
    1) "4"					//结果存入了mset6,值为4
    

    10) sinter 集合1 集合2
    获得两个集合的交集

    127.0.0.1:6379>smembers mset4
    1) "1"
    2) "2"
    3) "3"
    127.0.0.1:6379>smembers mset5
    1) "2"
    2) "3"
    3) "4"
    127.0.0.1:6379> sinter mset4 mset5
    1) "2"
    2) "3"
    

    11) sinterstore 新集合 集合1 集合2
    获得集合1和集合2的交集,并把结果存入新集合

    127.0.0.1:6379>sinterstore mset7 mset4 mset5
    (integer) 2
    127.0.0.1:6379>smembers mset7
    1) "2"
    2) "3"
    

    12) sunion 集合1 集合2
    获得指定集合的并集

    127.0.0.1:6379>sunion mset4 mset5
    1) "1"
    2) "2"
    3) "3"
    4) "4"
    

    13) sunionstore 新集合 集合1 集合2
    获得指定集合的并集,并把结果保存如新集合

    127.0.0.1:6379>sunionstore mset8 mset4 mset5
    (integer) 4
    127.0.0.1:6379>smembers mset8
    1) "1"
    2) "2"
    3) "3"
    4) "4"
    

    14) smove 源集合 目标集合 值
    将指定的值从源集合移动到目标集合

    127.0.0.1:6379>smembers mset1
    1) "1"
    2) "2"
    127.0.0.1:6379>smembers mset2
    1) "6"
    2) "7"
    127.0.0.1:6379>smove mset1 mset2 1
    (integer) 1
    127.0.0.1:6379>smembers mset1
    1) "2"
    127.0.0.1:6379>smembers mset2
    1) "1"
    2) "6"
    3) "7"
    

    参考资料:
    1.Redis http://redis.io
    2.Redis中文官方网站 http://www.redis.cn
    3.Redis 教程 | 菜鸟教程 http://www.runoob.com/redis/redis-tutorial.html

  • 相关阅读:
    anime.js 学习笔记
    swiper 报错 ‘ Can't find variable: Dom7’
    团队管理(二)
    团队管理(一)
    针对数值型数据的相关记录
    react+echarts折柱图实现
    侧边广告之心跳动画
    浅谈尾调用和尾递归
    elementUI 日期选择器获取CRON值
    elementUI 日期选择器之禁止年份事件二
  • 原文地址:https://www.cnblogs.com/52fhy/p/5007479.html
Copyright © 2011-2022 走看看