Introduce various uses and usage scenarios of Redis

Redis

1. Why use

  1. Solve application server cpu and memory pressure

  2. Reduce io read operations and reduce io pressure

  3. The scalability of relational databases is not strong, and it is difficult to change the table structure

2. Advantages:

  1. The nosql database has no relationship, the data structure is simple, and it is easier to expand the table

  2. Nosql has fast reading speed and fast processing of large data

3. Applicable scenarios:

  1. High concurrent read and write data

  2. Reading and writing of massive data

  3. Data that requires high scalability

4. Uncomfortable Scenarios:

  1. Requires transaction support (non-relational database)

  2. Based on sql structured query storage, the relationship is complex

5. Redis structure:

Redis is an open source key-value database that supports string, list, set, zset and hash type data. Operations on these data are atomic, and redus will periodically persist the data to ensure efficiency.

6. Usage scenarios:

  1. Cache with relational database

  • Cache frequently accessed data to reduce database io

  • Distributed architecture for session sharing

  1. Certain data can be persisted.

  • Use the zset type to store leaderboards

  • Use the natural time sorting of list to store the latest n data

7. Redis under Linux:

  1. redis directory: usr/local/bin

  2. Common commands of redis under linux:

  1. redis-benchmark: performance testing tool

  2. redis-server: start the redis server

  3. redis-cli: start the redis client and operate the entry

Eight, Redis basics

  1. Port: 6379

  2. Default 16 databases, subscripts start from 0

  3. Single thread: redis is single thread + io multiplexing: check the ready state of the file description

Memchached: multithreading + locks

  1. redis data type: String set list hash zset

Nine, Redis command:

  1. key operation

keys * View all keys in the current library
exists <key> Determine if there is a key
del <key> delete a key
expire <key> <second> Set the key expiration time unit is s seconds
ttl <key> Check how many seconds to expire -1 means not expired -2 ​​means expired
move <key> <db> Move the key to another library
dbsize Check the number of database keys
flushdb clear the current library
flushall Kill all libraries
  1. String type: String is binary safe and can contain any data source, up to 512m

get <key> View the corresponding key value
set <key> <value> Add key-value pair
append <key> <value> Appends the given value to the end of the original value
strlen < key > get value length
setnx <key> <value> Set key value when key does not exist
incr <key> Add 1 to the number stored in the key, if it is empty, the value is 1
decr <key> Subtract 1 from the number stored in key, or -1 if it is empty
incrby/decrby <key> <步长> Increase or decrease the number in the key

String batch processing:

mset <key1> <value1> <key2> <value2> Set multiple key-value pairs at the same time
mget <key1> <key 2> Get multiple values ​​at the same time
msetnx <key1> <value1> <key2> <value2> When none of the given keys exist
getrange <key> <start> <stop> similar to sunstring
setrange <key> <start> <stop> Similar to sunstring overwriting the original value
setex <key> <expiration time> <value> While setting the key value, give the expiration time
getset <key> <value> Trade-in, set the new value and get the old value
  1. List: linked list

1. Features:

single key multiple value

Redis lists are simple lists of strings, inserted from left or right

The bottom layer is a doubly linked list, which has high operation performance on both ends, and low query performance through subscripts

lpush/rpush <key> <value1> <value2> .. Insert multiple values ​​from left or right
lpop/rpop <key> Spit out a value from the left or right, the value light key will die
rpoplpush <key1> <key2> Spit out a value from the right of key1 to the left of key2
lrange <key> <index> Get elements by index subscript from left to right
lindex <key> <index> Get elements by index subscript from left to right
llen <key> get the length of the list get list length
linsert <key> before <value> <newvalue> Insert newvalue before value in key
  1. Set: An unordered collection similar to a list, which ensures that there will be no duplicate data in the list. The bottom layer is a hash table with a null value.

sadd <key> <value1> <value2> Add multiple elements to the key, duplicate values ​​are ignored
smembers <key> get all the values ​​of the set
sismember <key> <value> Judging whether the set key has the value value, there is 1, no 0
scard <key> Returns the number of elements in the collection
srem <key> <value1> <value2> remove an element from a collection
spop <key> Randomly spit out a value from the set
srandmember <key> <n> Randomly take n values ​​from the set, without removing from the set
smove <key1> <key2> <value> Move the value in key1 to key2
sinter <key1> <key2> Returns the intersection element of two sets
sunion <key1> <key2> 返回两个集合的并集
  1. hash:键值对集合,类似map<String,Object>

hset <key> <filed> <value> 给key 集合中的file 键赋值value
hget <key1> <field> 从key1 集合file取出value
hmset <key1> <field1> <value1> <field2> <value2> 批量设置hash的值
hexists <key> <field> 查看key中的field 是否存在
hkeys <key> 列出key中所有的filed
hvals <key> 列出该hash集合中所有的value
  1. zset:与set集合非常相似,每个成员都关联了score,可以用来排序

zadd<key><score1><value1><score2><value2> 将一个或多个元素以及score加入zset
zrange<key><start><stop> withscore 返回下标在区间内的集合,带有score
zrangebyscore <ket> <min> <max>[withscore] [limit offset count] 返回key中 score介于min和max中的成员,升序排列
zrevrangerbyscore <key> <min> <max> [withscore] [limit offset count] 降序
zincrby <key> <increment> <value> 在key集合中的value上增加increment
zrem <key> <value> 删除key集合下的指定元素
zcount <key> <min><max> 统计 区间内的元素个数
zcord <key> 获取集合中的元素个数
zrank <key><value> 查询value在key中的排名,从0开始

十、redis持久化:

  1. 两种方式:rdb(redis database)和aof(append of file)

  2. RDB:在指定时间间隔内,将内存中的数据作为一个快照文件(snapshot)写入到磁盘,读取的时候也是直接读取snapshot文件到内存中

①持久化过程:redis单独创建(fork)一个进程来持久化,会先将数据写入临时文件中,待上次持久化结束后,会将该临时文件替换上次持久化文件,比aof高效,但是最后一次数据可能会丢失

②Fork:在linux中,fork()会产生一个跟主进程一样的子进程,出于效率考虑,主进程和子进程会公用一段物理内存,当发生改变的时候,才会把主进程“”写时复制”一份给子进程

③Redis备份的文件:在redis.conf中设置,dbfilename默认为:dump.rdb

④ Rdb保存策略:

    1. 900s 1 file change

    2. 300s 10file change

    3. 60s 10000file change

⑤Rdb的备份:

    1. config get dir 得到备份的文件夹

    2. 复制备份文件

⑥Rdb恢复:

    1. 关闭redis

    2. 将备份文件复制到工作目录下

    3. 启动redis,自动加载

  1. AOF : 以日志形式记录每个写操作,启动时通过日志恢复操作

    1. 开启AOF:默认不开启,进入redis.conf找到appendonly yes打开

    2. 修复AOF:redis-check-aof –fix appendonly.aof

    3. 同步频率:每秒记录一次,如果宕机该秒记可能失效

    4. Rewrite:bgrewriteaof 因为日志是追加方式,文件会越来越大,当超过了设置的阈值时,日志文件会压缩,保留仅可以恢复的日志

  2. RDB和AOF对比

    1. 节省磁盘空间

    2. 恢复速度快

    3. RDB优点:

    1. ROD缺点:

    1. 数据太大时,比较消耗性能

    2. 一段时间保存一次快照,宕机时最后一次可能没有保存

c) AOF优点:

i. 备份机制更加稳健

ii. 可读的日志文件,通过aof恢复更加稳健,可以处理失误

d) AOF缺点:

i. 比RDB更占磁盘

ii. 备份速度较慢

    1. iii每次都同步日志,有性能压力

  1. RDB和AOF哪个好

    1. 官方推荐都启用

    2. 对数据不敏感,单独用RDB

    3. 不建议单独使用AOF

    4. 若作为纯缓存使用,可以都不开启

十一、Redis事务:输入multi,输入的命令都会依次进入到队列中,但不会执行,直到输入exec,redis会将之前命令队列中的命令依次执行,通过discard可以放弃组队。

  1. 主要作用:序列化操作,串联多个命令防止别的命令插队

  2. 悲观锁:每次拿到数据的时候都会上锁,或者等待别人处理完再去拿锁,传统的关系型数据库里边很多用到了这种锁机制,比如行锁、表锁、读锁、写锁

  3. 乐观锁:每次拿数据的时候总认为别人不会修改数据,所以不会上锁。但是更新的时候回去判断别人有没有更改数据,使用版本号机制。乐观锁适用于多读的应用类型,可以提高吞吐量。

  4. Redis使用乐观锁:redis就是利用check-and-set机制实现事务

  5. 三大特性:

    1. 单独的隔离操作:事务中的所有命令都会序列化,按顺序执行。不会被其他客户端打断

    2. 没有隔离级别概念:队列中的命令没有提交之前不会被执行,事务外不能查看事务内的更新

    3. 不能保证原子性:跳过错误,依旧执行,没有回滚

十二、Redis订阅/发布:

是进程中的一种消息通信模式,发送者pub发送消息,订阅者sub接收消息 剩下的略。。。

十三、Redis主从复制:

  1. 是什么:主从复制就是主机数据更新后根据配置和策略,自动同步到备份机的master/slaver机制,master写为主,slave读为主

  2. 用处:

    1. 读写分离,性能拓展。

    2. 容灾快速恢复

  3. 配置服务器(配从不配主):

    1. 拷贝多个redis.conf文件

    2. 开启daemonize yes

    3. Pid文件名字

    4. 指定端口

    5. Log文件名字

    6. Dump.rdb名字

    7. Appendonly 关掉或者换名字

十四、Jedis:

  1. 所需jar包:

    1. common-pool-1.6jar包

    2. jedis-2.1

  2. 获取jedis对象:Jedis jedis = new Jedis(“ip” ,端口号);

十五、集群分布:

实现对redis的水平拓展,启动n’的redis节点,将整个数据分布在这n个节点中

  1. 配置conf文件:

    1. 拷贝多个redis.conf文件

    2. 开启daemonize yes

    3. Pid文件名字

    4. 指定端口

    5. Log文件名字

    6. Dump.rdb名字

    7. Appendonly 关掉或者换名字

  2. 配置cluster文件:

    1. cluster-enable yes 打开集群模式

    2. cluster-config-file xxx.conf 设置生成的节点配置文件名

    3. cluster-node-timeout 15000设置节点失联时间,超多该时间(毫秒),集群自动进入主从切换

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324491645&siteId=291194637