redis笔记
一、了解redis
导读模块:至于什么是缓存我们今天不过多的赘述了,那么为什么要使用redis呢,要解答这个问题我们还要从软件项目的架构演变的历程来感悟
-
单机时代,存储只用一台机器装mysql,如果每次存储成千上万条数据,这样很会导致mysql的性能很差,存储以及读取速度很慢,然后就演变成缓存+mysql+垂直拆分的方式。
Cache作为中间缓存时代,将所有的数据先保存到缓存中,然后再存入mysql中,减小数据库压力,提高效率。
但是当数据再次增加到又一个量级,上面的方式也不能满足需求,由于数据库的写入压力增加,缓存只能缓解数据库的读取压力。读写集中在一个数据库上让数据库不堪重负,大部分网站开始使用主从复制技术来达到读写分离,以提高读写性能和读库的可扩展性。Mysql的master-slave模式成为这个时候的网站标配了。
-
主从分离模式时代,在redis的高速缓存,MySQL的主从复制,读写分离的基础之上,这时MySQL主库的写压力开始出现瓶颈,而数据量的持续猛增,由于MyISAM使用表锁,在高并发下会出现严重的锁问题,大量的高并发MySQL应用开始使用InnoDB引擎代替MyISAM
-
Nosql数据库的时代
-
易扩展
这些类型的数据存储不需要固定的模式,无需多余的操作就可以进行横向的扩展。相对于关系型数据库可以减少表和字段特别多的情况。也无疑之间在架构的层面上带来了可扩展的能力
-
大数据量提高性能
-
多样灵活的数据模型
-
帮助理解:
-
补充讲解:问mysql架构中也是有缓存的,服务器中查询缓存(query cache),在执行sql语句的时候,会将可以作为缓存的sql结果保存在查询缓存中,这样当有相同的sql查询执行时,可以直接从缓存中查询到结果,不需要进行sql解析、优化器优化,为什么还要用redis?
- 这个缓存是本地缓存,如果有多台服务器,sql语句会随机发送给其中一台,无法保证相同的请求会发送给同一台,这样本地缓存命中率就比较低,本地缓存(即查询缓存)就没有什么用了
- 从查询缓存中取出结果或者将查询结果添加进查询缓存中,会带来额外性能消耗
- 当表的结构或内容发生变化时,使用这个表的缓存查询将不再有效,查询缓存值的相关条目将被清空。常见修改表结构和表内容的语句,如delete、insert、altert table很多。使用redis作为缓存将受这个影响很小,因为它是基于键值对保存缓存的,只有key对应的缓存内容发生变化,才会受到影响,其他key对应缓存内容发生变化对其几乎是没有影响的
- 简而言之:redis可以用在多个服务器(分布式业务中),且消耗比较低,且数据类型丰富
拓展提升讲解(普及了解即可):nosql之redis的应用
- 1) 大数据时代淘宝、微信、以及微博等都广泛的使用了redis数据库,将一些固定不变的数据例如学校,区域等固定的信息保存在关系型数据库中。然后对于经常变化的数据例如淘宝每个节日都会有比较热门的搜索显示在搜索框,当节日过去关键字自动删除,为了便于管理,可以将这些数据保存在redis数据库中,并设置过期时间,到达时间就自动删除。
- 2)为了缓解数据库压力,微博服务端首先将发送的微博消息保存到redis数据库,自己可以立即查看到,然后将内存中的数据同步到关系型数据库。
二、redis的概念
- redis:Redis 是一个高性能的key-value形式的数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部分场合可以对关系数据库起到很好的补充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端,使用很方便.
备注:其实我们作为java开发程序员只是需要用到相应的java的支持redis操作的jar包即可,但是为了应付面试我们必须要多讲
-
redis的特点:
- 内存数据库,速度快,也支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
备注:Redis读的速度是110000次/s,写的速度是81000次/s ,且是单台服务器的 - Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
- Redis支持数据的备份,即master-slave模式的数据备份。
- 支持事务
- 内存数据库,速度快,也支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
-
redis的使用场景:
- 数据高并发的读写
- 海量数据的读写
- 对扩展性要求高的数据
三、redis.conf的详解(了解即可)
# Redis配置文件样例
# Note on units: when memory size is needed, it is possible to specifiy
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.
# Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程
# 启用守护进程后,Redis会把pid写到一个pidfile中,在/var/run/redis.pid
daemonize no
# 当Redis以守护进程方式运行时,Redis默认会把pid写入/var/run/redis.pid文件,可以通过pidfile指定
pidfile /var/run/redis.pid
# 指定Redis监听端口,默认端口为6379
# 如果指定0端口,表示Redis不监听TCP连接
port 6379
# 绑定的主机地址
# 你可以绑定单一接口,如果没有绑定,所有接口都会监听到来的连接
# 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,表示关闭该功能
timeout 0
# 指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认为verbose
# debug (很多信息, 对开发/测试比较有用)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel verbose
# 日志记录方式,默认为标准输出,如果配置为redis为守护进程方式运行,而这里又配置为标准输出,则日志将会发送给/dev/null
logfile stdout
# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no
# Specify the syslog identity.
# syslog-ident redis
# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0
# 设置数据库的数量,默认数据库为0,可以使用select <dbid>命令在连接上指定数据库id
# dbid是从0到‘databases’-1的数目
databases 16
################################ SNAPSHOTTING #################################
# 指定在多长时间内,有多少次更新操作,就将数据同步到数据文件,可以多个条件配合
# Save the DB on disk:
#
# save <seconds> <changes>
#
# Will save the DB if both the given number of seconds and the given
# number of write operations against the DB occurred.
#
# 满足以下条件将会同步数据:
# 900秒(15分钟)内有1个更改
# 300秒(5分钟)内有10个更改
# 60秒内有10000个更改
# Note: 可以把所有“save”行注释掉,这样就取消同步操作了
save 900 1
save 300 10
save 60 10000
# 指定存储至本地数据库时是否压缩数据,默认为yes,Redis采用LZF压缩,如果为了节省CPU时间,可以关闭该选项,但会导致数据库文件变的巨大
rdbcompression yes
# 指定本地数据库文件名,默认值为dump.rdb
dbfilename dump.rdb
# 工作目录.
# 指定本地数据库存放目录,文件名由上一个dbfilename配置项指定
#
# Also the Append Only File will be created inside this directory.
#
# 注意,这里只能指定一个目录,不能指定文件名
dir ./
################################# REPLICATION #################################
# 主从复制。使用slaveof从 Redis服务器复制一个Redis实例。注意,该配置仅限于当前slave有效
# so for example it is possible to configure the slave to save the DB with a
# different interval, or to listen to another port, and so on.
# 设置当本机为slav服务时,设置master服务的ip地址及端口,在Redis启动时,它会自动从master进行数据同步
# slaveof <masterip> <masterport>
# 当master服务设置了密码保护时,slav服务连接master的密码
# 下文的“requirepass”配置项可以指定密码
# masterauth <master-password>
# When a slave lost the connection with the master, or when the replication
# is still in progress, the slave can act in two different ways:
#
# 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will
# still reply to client requests, possibly with out of data data, or the
# data set may just be empty if this is the first synchronization.
#
# 2) if slave-serve-stale data is set to 'no' the slave will reply with
# an error "SYNC with master in progress" to all the kind of commands
# but to INFO and SLAVEOF.
#
slave-serve-stale-data yes
# Slaves send PINGs to server in a predefined interval. It's possible to change
# this interval with the repl_ping_slave_period option. The default value is 10
# seconds.
#
# repl-ping-slave-period 10
# The following option sets a timeout for both Bulk transfer I/O timeout and
# master data or ping response timeout. The default value is 60 seconds.
#
# It is important to make sure that this value is greater than the value
# specified for repl-ping-slave-period otherwise a timeout will be detected
# every time there is low traffic between the master and the slave.
#
# repl-timeout 60
################################## SECURITY ###################################
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
# 设置Redis连接密码,如果配置了连接密码,客户端在连接Redis时需要通过auth <password>命令提供密码,默认关闭
# requirepass foobared
# Command renaming.
#
# It is possilbe to change the name of dangerous commands in a shared
# environment. For instance the CONFIG command may be renamed into something
# of hard to guess so that it will be still available for internal-use
# tools but not available for general clients.
#
# Example:
#
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
#
# It is also possilbe to completely kill a command renaming it into
# an empty string:
#
# rename-command CONFIG ""
################################### LIMITS ####################################
# 设置同一时间最大客户端连接数,默认无限制,Redis可以同时打开的客户端连接数为Redis进程可以打开的最大文件描述符数,
# 如果设置maxclients 0,表示不作限制。当客户端连接数到达限制时,Redis会关闭新的连接并向客户端返回max Number of clients reached错误信息
# maxclients 128
# Don't use more memory than the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys with an
# EXPIRE set. It will try to start freeing keys that are going to expire
# in little time and preserve keys with a longer time to live.
# Redis will also try to remove objects from free lists if possible.
#
# If all this fails, Redis will start to reply with errors to commands
# that will use more memory, like SET, LPUSH, and so on, and will continue
# to reply to most read-only commands like GET.
#
# WARNING: maxmemory can be a good idea mainly if you want to use Redis as a
# 'state' server or cache, not as a real DB. When Redis is used as a real
# database the memory usage will grow over the weeks, it will be obvious if
# it is going to use too much memory in the long run, and you'll have the time
# to upgrade. With maxmemory after the limit is reached you'll start to get
# errors for write operations, and this may even lead to DB inconsistency.
# 指定Redis最大内存限制,Redis在启动时会把数据加载到内存中,达到最大内存后,Redis会先尝试清除已到期或即将到期的Key,
# 当此方法处理后,仍然到达最大内存设置,将无法再进行写入操作,但仍然可以进行读取操作。
# Redis新的vm机制,会把Key存放内存,Value会存放在swap区
# maxmemory <bytes>
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached? You can select among five behavior:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key accordingly to the LRU algorithm
# volatile-random -> remove a random key with an expire set
# allkeys->random -> remove a random key, any key
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# noeviction -> don't expire at all, just return an error on write operations
#
# Note: with all the kind of policies, Redis will return an error on write
# operations, when there are not suitable keys for eviction.
#
# At the date of writing this commands are: set setnx setex append
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
# getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy volatile-lru
# LRU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can select as well the sample
# size to check. For instance for default Redis will check three keys and
# pick the one that was used less recently, you can change the sample size
# using the following configuration directive.
#
# maxmemory-samples 3
############################## APPEND ONLY MODE ###############################
#
# Note that you can have both the async dumps and the append only file if you
# like (you have to comment the "save" statements above to disable the dumps).
# Still if append only mode is enabled Redis will load the data from the
# log file at startup ignoring the dump.rdb file.
# 指定是否在每次更新操作后进行日志记录,Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一段时间内的数据丢失。
# 因为redis本身同步数据文件是按上面save条件来同步的,所以有的数据会在一段时间内只存在于内存中。默认为no
# IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
# log file in background when it gets too big.
appendonly no
# 指定更新日志文件名,默认为appendonly.aof
# appendfilename appendonly.aof
# The fsync() call tells the Operating System to actually write data on disk
# instead to wait for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
# 指定更新日志条件,共有3个可选值:
# no:表示等操作系统进行数据缓存同步到磁盘(快)
# always:表示每次更新操作后手动调用fsync()将数据写到磁盘(慢,安全)
# everysec:表示每秒同步一次(折衷,默认值)
appendfsync everysec
# appendfsync no
# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
#
# In order to mitigate this problem it's possible to use the following option
# that will prevent fsync() from being called in the main process while a
# BGSAVE or BGREWRITEAOF is in progress.
#
# This means that while another child is saving the durability of Redis is
# the same as "appendfsync none", that in pratical terms means that it is
# possible to lost up to 30 seconds of log in the worst scenario (with the
# default Linux settings).
#
# If you have latency problems turn this to "yes". Otherwise leave it as
# "no" that is the safest pick from the point of view of durability.
no-appendfsync-on-rewrite no
# Automatic rewrite of the append only file.
# Redis is able to automatically rewrite the log file implicitly calling
# BGREWRITEAOF when the AOF log size will growth by the specified percentage.
#
# This is how it works: Redis remembers the size of the AOF file after the
# latest rewrite (or if no rewrite happened since the restart, the size of
# the AOF at startup is used).
#
# This base size is compared to the current size. If the current size is
# bigger than the specified percentage, the rewrite is triggered. Also
# you need to specify a minimal size for the AOF file to be rewritten, this
# is useful to avoid rewriting the AOF file even if the percentage increase
# is reached but it is still pretty small.
#
# Specify a precentage of zero in order to disable the automatic AOF
# rewrite feature.
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
################################## SLOW LOG ###################################
# The Redis Slow Log is a system to log queries that exceeded a specified
# execution time. The execution time does not include the I/O operations
# like talking with the client, sending the reply and so forth,
# but just the time needed to actually execute the command (this is the only
# stage of command execution where the thread is blocked and can not serve
# other requests in the meantime).
#
# You can configure the slow log with two parameters: one tells Redis
# what is the execution time, in microseconds, to exceed in order for the
# command to get logged, and the other parameter is the length of the
# slow log. When a new command is logged the oldest one is removed from the
# queue of logged commands.
# The following time is expressed in microseconds, so 1000000 is equivalent
# to one second. Note that a negative number disables the slow log, while
# a value of zero forces the logging of every command.
slowlog-log-slower-than 10000
# There is no limit to this length. Just be aware that it will consume memory.
# You can reclaim memory used by the slow log with SLOWLOG RESET.
slowlog-max-len 1024
################################ VIRTUAL MEMORY ###############################
### WARNING! Virtual Memory is deprecated in Redis 2.4
### The use of Virtual Memory is strongly discouraged.
### 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.
# 指定是否启用虚拟内存机制,默认值为no,
# VM机制将数据分页存放,由Redis将访问量较少的页即冷数据swap到磁盘上,访问多的页面由磁盘自动换出到内存中
# 把vm-enabled设置为yes,根据需要设置好接下来的三个VM参数,就可以启动VM了
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.
#
# Redis交换文件最好的存储是SSD(固态硬盘)
# 虚拟内存文件路径,默认值为/tmp/redis.swap,不可多个Redis实例共享
# *** 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
# 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的数据存入虚拟内存,无论vm-max-memory设置多少,所有索引数据都是内存存储的(Redis的索引数据就是keys)
# 也就是说当vm-max-memory设置为0的时候,其实是所有value都存在于磁盘。默认值为0
vm-max-memory 0
# Redis swap文件分成了很多的page,一个对象可以保存在多个page上面,但一个page上不能被多个对象共享,vm-page-size是要根据存储的数据大小来设定的。
# 建议如果存储很多小对象,page大小最后设置为32或64bytes;如果存储很大的对象,则可以使用更大的page,如果不确定,就使用默认值
vm-page-size 32
# 设置swap文件中的page数量由于页表(一种表示页面空闲或使用的bitmap)是存放在内存中的,在磁盘上每8个pages将消耗1byte的内存
# swap空间总容量为 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.
# 设置访问swap文件的I/O线程数,最后不要超过机器的核数,如果设置为0,那么所有对swap文件的操作都是串行的,可能会造成比较长时间的延迟,默认值为4
vm-max-threads 4
############################### ADVANCED CONFIG ###############################
# 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.
# 指定是否激活重置哈希,默认为开启
activerehashing yes
################################## INCLUDES ###################################
# 指定包含其他的配置文件,可以在同一主机上多个Redis实例之间使用同一份配置文件,而同时各实例又拥有自己的特定配置文件
# include /path/to/local.conf
# include /path/to/other.conf
四、redis的基本操作
redis的指令操作
操作 | 指令 |
---|---|
查看redis的版本 | redis-server -v |
启动redis | sudo /etc/init.d/redis-server start |
关闭redis | sudo /etc/init.d/redis-server stop |
重启redis | sudo /etc/init.d/redis-server restart |
查看redis状态 | sudo /etc/init.d/redis-server status |
退出redis的客户端 | exit |
清除单个数据库中的数据 | flushdb |
清除全部数据库中的数据 | flushall |
因为redis安装之后默认有16个数据库,且默认是在其第一个数据库中进行操作的,如果想要切换数据库 | select 1/2/3/4/5… |
五、配置
1、配置redis的访问密码
导读模块:redis经常被用来充当缓存,就是这样一个角色是不需要为其设定密码的,但是为了应付面试 ,我们还是要讲解为redis配置访问密码
步骤:
- 在终端中用vi编辑器打开redis的配置文件:sudo vi /etc/redis/redis.conf
- 在redis.conf中的大约是391行附近添加上密码:
- 先按i这个健使其进入可写入模式,
- 添加上requirepass 1234
- 先按esc这个健,然后输入小写的的:wq!即可
- 修改后,重启Redis服务器:sudo /etc/init.d/redis-server restart
- 再次用无密码和有密码分别登录一次
为redis添加密码
redis添加完密码之后重启且成功
redis添加完密码之后重新用密码登录和不用密码登录的效果
2、配置redis的远程连接
导读模块:默认情况下,Redis服务器不允许远程访问,只允许本机访问,所以我们需要设置打开远程访问的功能。
步骤:
-
用vi打开Redis服务器的配置文件redis.conf: sudo vi /etc/redis/redis.conf
-
将redis.conf文件中大概第69行左右的127.0.0.1给注释掉
-
修改后,重启Redis服务器: sudo /etc/init.d/redis-server restart
-
查Redis的网络监听端口: netstat -nlt|grep 6379
可以参考图片:redis远程连接的配置1
redis远程连接的配置2
六、redis的5种数据类型
1、String(字符串)
string是redis最基本的类型,你可以理解成与Memcached一模一样的类型,一个key对应一个value。
string类型是二进制安全的。意思是redis的string可以包含任何数据。比如jpg图片或者序列化的对象 。
string类型是Redis最基本的数据类型,一个键最大能存储512MB
例子1:先用redis-cli连接上redis的服务端或者用工具也行
set name wyh
get name
小结:set 赋值,get 取值
例子2.redis中的string类型来处理value的值为数字的时候,在遇到数值操作时,会自动转换过为字符串,如写入数字1,读出来将是字符串1
incr age 默认是从0开始的,每执行一次就自动的加1
get age 取出的值是“1”
incr age 再次执行之后得到的值就是2
get age 取出的值为“2”
小结: incr 整数递增:存入整形数字值,且默认是从0开始的
除了以上这两个常用的指令方法以外还有很多,详细请看下面的(常用的要记住,不常用的回查找)
关键字 | 命令 | 语法 |
---|---|---|
SET,GET | 赋值,赋值 | GET key,SET key value value如果有空格需要双引号以示区分 |
INCR | 整数递增 | INCR key 默认值为0,所以首先执行命令得到 1 ,不是整型提示错误 |
INCRBY | 增加指定的整数 | INCRBY key increment |
DECR | 整数递减 | DECR key 默认值为0,所以首先执行命令得到 -1,不是整型提示错误 |
DECRBY | 减少指定的整数 | DECRBY key increment |
INCRBYFLOAT | 增加指定浮点数 | INCRBYFLOAT key increment 与INCR命令类似,只不过可以递增一个双精度浮点数 |
APPEND | 向尾部追加值 | APPEND key value redis客户端并不是输出追加后的字符串,而是输出字符串总长度 |
STRLEN | 获取字符串长度 | STRLEN key 如果键不存在返回0,注意如果有中文时,一个中文长度是3,redis是使用UTF-8编码中文的 |
MGET | 获取多个键值 | MGET key [key …] 例如:MGET key1 key2 |
MSET | 设置多个键值 | MSET key value [key value …] 例如:MSET key1 1 key2 “hello redis” |
GETBIT | 二进制指定位置值 | GETBIT key offset 例如:GETBIT key1 2 ,key1为hello 返回 1,返回的值只有0或1,当key不存在或超出实际长度时为0 |
SETBIT | 设置二进制位置值 | SETBIT key offset value ,返回该位置的旧值 |
BITCOUNT | 二进制是1的个数 | BITCOUNT key [start end] ,start 、end为开始和结束字节 |
BITOP | 位运算 | BITOP operation destkey key [key …] ,operation支持AND、OR、XOR、NOT |
BITPOS | 偏移 | BITPOS key bit [start] [end] |
2、Hash(哈希)
Redis hash 是一个键值(key=>value)对集合。
Redis hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象
例子1:向redis中存入一个对象,且key为 user value值为【id “001” name “杨过” sex “男” age 31】
hmset user id "001" name "杨过" sex "男" age 31
// id,name,sex,age这些都是value中的filed
hget user name //取出对象中的某一个属性值
hmget user id name sex //取出对象中的多个属性值
HGETALL user //取出该对象的全部的属性值
备注:如果遇到中文的时候,可能会显示的为乱码,但是这个不是错误是因为redis-cli客户端没有进行显示设置,则需要先exit退出,然后重新登录redis-cli --raw 然后重启搞一遍即可
针对Hash类型的数据的操作的指令方法有那些:
关键字 | 命令 | 语法 |
---|---|---|
HSET | 设置单个 | HSET key field value,不存在时返回1,存在时返回0,没有更新和插入之分 |
HMSET | 设置多个 | HMSET key field value [field value …] |
HGET | 读取单个 | HGET key field,不存在是返回nil |
HMGET | 读取多个 | HMGET key field [field …] |
HGETALL | 读取全部 | HGETALL key,返回时字段和字段值的列表 |
HEXISTS | 判断字段是否存在 | HEXISTS key field,存在返回1 ,不存在返回0 |
HSETNX | 字段不存在时赋值 | HSETNX key field value,与hset命令不同,hsetnx是键不存在时设置值 |
HINCRBY | 增加数字 | HINCRBY key field increment ,返回增加后的数,不是整数时会提示错误 |
HDEL | 删除字段 | HDEL key field [field …] ,返回被删除字段的个数 |
HKEYS | 只获取字段名 | HKEYS key ,返回键的所有字段名 |
HVALS | 只获取字段值 | HVALS key ,返回键的所有字段值 |
HLEN | 字段数量 | HLEN key ,返回字段总数 |
3、List(列表)
Redis 列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边),列表最多可存储 232次幂 - 1 元素 (4294967295, 每个列表可存储40多亿)
例子1:向redis中添加一个list类型的数据
lpush name wyh //从左边开始压入list中
lpush name china
llen name //获取list的长度
lrange name 0 -1 //获取当前list中的全部数据
结果:china wyh
list类型数据的指令函数有:
关键字 | 命令 | 语法 |
---|---|---|
LPUSH | 添加左边元素 | LPUSH key value [value …] ,返回添加后的列表元素的总个数 |
RPUSH | 添加右边元素 | RPUSH key value [value …] ,返回添加后的列表元素的总个数 |
LPOP | 移除左边第一个元素 | LPOP key ,返回被移除的元素值 |
RPOP | 移除右边第一个元素 | RPOP key ,返回被移除的元素值 |
LLEN | 列表元素个数 | LLEN key, 不存在时返回0,redis是直接读取现成的值,并不是统计个数 |
LRANGE | 获取列表片段 | LRANGE key start stop,如果start比stop靠后时返回空列表,0 -1 返回整个列表; 正数时:start 开始索引值,stop结束索引值(索引从0开始) 负数时:例如 lrange num -2 -1,-2表示最右边第二个,-1表示最右边第一个, |
LREM | 删除指定值 | LREM key count value,返回被删除的个数 count>0,从左边开始删除前count个值为value的元素 count<0,从右边开始删除前 count=0,删除所有值为value的元素 使用方法:lrem的使用讲解 |
LINDEX | 索引元素值 | LINDEX key index ,返回索引的元素值,-1表示从最右边的第一位 lindex list 0 |
LSET | 设置元素值 | LSET key index value LSET list -1 123 |
LTRIM | 保留列表片段 | LTRIM key start stop,start、top 参考lrange命令 |
RPOPLPUSH | 一个列表转移另一个列表 | RPOPLPUSH source desctination ,从source列表转移到desctination列表 该命令分两步看,首先source列表RPOP右移除,再desctination列表LPUSH |
lrem的使用讲解
4、Set(集合)
set集合类型值具有唯一性,常用操作是向集合添加、删除、判断某个值是否存在,集合内部是使用值为空的散列表实现的。
集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。
例子1:向redis中添加set类型的数据
sadd ball football
sadd ball basketball
sadd ball tabletinnes
sadd ball football 重复数据,插入无效
smembers ball 查看数据,获取全部元素
小结:sadd 命令:添加一个 string 元素到 key 对应的 set 集合中,成功返回1,如果元素已经在集合中返回 0,如果 key 对应的 set 不存在则返回错误
smembers命令:获取全部元素
set类型数据的指令函数:
关键字 | 命令 | 语法 |
---|---|---|
SADD | 添加元素 | SADD key member [member …] ,向一个集合添加一个或多个元素,因为集合的唯一性, 所以添加相同值时会被忽略。返回成功添加元素的数量。 |
SREM | 删除元素 | SREM key member [member …] 删除集合中一个或多个元素,返回成功删除的个数。 例如:srem ball football basketball |
SMEMBERS | 获取全部元素 | SMEMBERS key ,返回集合全部元素 |
SISMEMBER | 值是否存在 | SISMEMBER key member ,如果存在返回1,不存在返回0 例如:sismember ball football |
SDIFF | 差运算 | SDIFF key [key …] ,例如:集合A和集合B,差集表示A-B,在A里有的元素B里没有,返回差集合;多个集合(A-B)-C |
SINTER | 交运算 | SINTER key [key …],返回交集集合,每个集合都有的元素 |
SUNION | 并运算 | SUNION key [key …],返回并集集合,所有集合的元素 |
SCARD | 集合元素个数 | SCARD key ,返回集合元素个数 |
*STROE | 集合运算后存储结果 | SDIFFSTROE destination key [key …] ,差运算并存储到destination新集合中 |
*STROE | 集合运算后存储结果 | SINTERSTROE destination key [key …],交运算并存储到destination新集合中 |
*STROE | 集合运算后存储结果 | SUNIONSTROE destination key [key …],并运算并存储到destination新集合中 |
SRANDMEMGER | 随机获取元素 | SRANDMEMBER key [count],根据count不同有不同结果, count大于元素总数时返回全部元素 count>0 ,返回集合中count不重复的元素 |
SPOP | 弹出元素 | SPOP key [count] ,因为集合是无序的,所以spop会随机弹出一个元素 |
5、zset(sorted set:有序集合)
zset: set类型的升级版,该类型是有序的。因为是有序的,在添加元素的时候需要指定顺序
例子1:向redis中添加zset类型的数据
zadd ball 1 football
zadd ball 2 basketball
zadd ball 0 tabletinnes
zadd ball 1 football
zrange ball 0 -1
显示的结果为有序的: tabletinnes football basketball
zset类型数据的指令函数有:
关键字 | 命令 | 语法 |
---|---|---|
ZADD | 添加集合元素 | ZADD key [NX|XX], [CH] ,[INCR] score member [score member …],不存在添加,存在更新。 |
ZSCORE | 获取元素分数 | ZSCORE key member ,返回元素成员的score 分数 |
ZRANGE | 元素小到大 | ZRANGE key start top [WITHSCORES] ,参考LRANGE ,加上withscores 返回带元素,即元素,分数;当分数一样时,按元素排序 |
ZREVRANGE | 元素大到小 | ZREVRANGE key start [WITHSCORES] ,与zrange区别在于zrevrange是从大到小排序 |
ZRANGEBYSCORE | 指定分数范围元素 | ZRANGEBYSCORE key min max [WITHSCORE] [LIMIT offest count] 返回从小到大的在min和max之间的元素,( 符号表示不包含,例如:80-100,(80 100, withscore返回带分数 limit offest count 向左偏移offest个元素,并获取前count个元素 |
ZREVRANGESCORE | 指定分数范围元素 | ZREVRANGEBYSCORE key max min [WITHSCORE] [LIMIT offest count] 与zrangebyscore类似,只不过该命令是从大到小排序的。 |
ZINCRBY | 增加分数 | ZINCRBY key increment member ,注意是增加分数,返回增加后的分数; 如果成员不存在,则添加一个为0的成员 参考例子:redis5种数据类型之zset种zincrby指令的使用 |
redis5种数据类型之zset种zincrby指令的使用
6、 5种数据类型的使用场景
1.String使用场景:
- 常规key-value缓存应用。
- 常规计数: 微博数, 粉丝数, 点赞,视频播放量,每播放一次就+1
(实现方式:String在redis内部存储默认就是一个字符串,被redisObject所引用, 当遇到incr,decr等操作时会转成数值型进行计算,此时redisObject的encoding字段为int) - 接口防刷:验证码登录,公司一般的验证码等发短信功能都是调用的第三方接口,如果被有心之人利用了,会给公司造成一定的损失,所以简单的解决方法就是限流(其实就是限定验证码的值在缓存中有效时间为60秒这样的做法)
2.Hash使用场景:
- 存储用户信息
- 存储部分变更数据
3.List使用场景:
- twitter的关注列表,粉丝列表等都可以用Redis的list结构来实现
- 最新消息排行等功能(比如朋友圈的时间线)
- 消息队列
4.Set 使用场景:
- 共同好友
- 利用唯一性,统计访问网站的所有独立ip
5.ZSet使用场景:
- 在线游戏的排行榜/热搜排行榜
小结:redis的5种数据类型是需要巧妙的运用才能发挥其作用的