Redis learning summary Redis summary

Redis summary

Introduction to Redis


Redis:开源、免费、高性能、K-V数据库、内存数据库、非关系型数据库,支持持久化、集群和事务

Redis installation and configuration


  1. Run Redis with docker
docker pull redis
docker run -d --name redis -p 6379:6379 redis
docker exec -it redis redis-cli
  1. Linux installation
  1. Make sure that Linux has gcc installed
  2. Download Redis
    wget http://download.redis.io/releases/redis-4.0.1.tar.gz
  3. Unzip
    tar -zxvf redis-4.0.1.tar.gz
  4. Compile after entering the directory
    cd redis-4.0.1
    make MALLOC=libc
  5. Installation
    make PREFIX=/usr/local/redis install#Specify the installation directory as /usr/local/redis
  6. start up
    /usr/local/redis/bin/redis-server
  1. Redis configuration
  1. Enter the decompressed Redis directory and copy redis.conf to the directory of the installation file
    cp redis.conf /usr/local/redis
  2. Start Redis with custom configuration
    /usr/local/redis/bin/redis-server /usr/local/redis/redis.conf
  1. Detailed configuration
  • daemonize: the default is no, modify it to yes to enable the daemon thread
  • port: set the port number, the default is 6379
  • bind: Bind the IP address
  • databases: the number of databases, the default is 16
  • save <second> <changes>: Specify how many times and how many update operations, and then synchronize the data to the data file
    #redis默认配置有三个条件,满足一个即进行持久化
    save 900 1#900s有1个change
    save 300 10#300s有10个change
    save 60 10000#60s有10000change
  • dbfilename: Specify the file name of the local database, the default is dump.rdb
  • dir: Specify the storage directory of the local database, the default is ./current folder
  • requirepass: set a password, closed by default
    redis -cli -h host -p port -a password
  1. Redis is off
  • Use the kill command (abnormal shutdown, data is easy to lose)
    ps -ef|grep -i redis
    kill -9 PID
  • Normal shutdown
    redis-cli shutdown

Redis common commands


Redis five data types: string, hash, list, set, zset

Public command
  • DEL key
  • DUMP key: serialize the given key and return the serialized value
  • EXISTS key: check whether the key exists
  • EXPIRE key second: Set the expiration time for the key
  • TTL key: Return the remaining time of the key
  • PERSIST key: Remove the expiration time of the key, and the key will be stored persistently
  • KEY pattern: Query the key of a given pattern of all symbols
  • RANDOM key: return a key randomly
  • RANAME key newkey: modify the name of the key
  • MOVE key db: Move the key to the specified database
  • TYPE key: Returns the type of the value stored in the key
EXPIRE key second的使用场景:
1、限时的优惠活动
2、网站数据缓存
3、手机验证码
4、限制网站访客频率
Key naming suggestions
  1. The key should not be too long, try not to exceed 1024 bytes. Not only consumes memory, but also reduces the efficiency of search
  2. The key should not be too short, too short will reduce the readability
  3. In a project, it is best to use a unified naming scheme for the key, such as user:123:password
  4. Key is case sensitive

string

The string type is binary safe, and the redis string can contain any data, such as images and serialized objects. One key can store up to 512MB. ==Binary security means that when data is transmitted, the information security of binary data can be guaranteed, that is, it will not be tampered with or deciphered; if it is attacked, it can be detected in time ==

  • setkey_name value : The command is not case sensitive, but the key_name is case sensitive
  • SETNX key value : Set the value of the key when the key does not exist. (SET if Not eXists)
  • get key_name
  • GETRANGE key start end: Get the substring of the string in the key, starting from start and ending with end
  • MGET key1 [key2 …]: Get multiple keys
  • GETSET KEY_NAME VALUE: Set the value of the key and return the old value of the key. When the key does not exist, return nil
  • STRLEN key: Returns the length of the string stored in the key
  • INCR KEY_NAME : The value stored in the key of the INCR command is +1, if there is no key, the value in the key is initialized to 0 and then added to 1.
  • INCRBY KEY_NAME increment
  • DECR KEY_NAME : The value in the key is decremented by one
  • DECRBY KEY_NAME
  • append key_name value: string splicing, append to the end, if it does not exist, assign a value to it

String application scenarios:

1、String通常用于保存单个字符串或JSON字符串数据
2、因为String是二进制安全的,所以可以把保密要求高的图片文件内容作为字符串来存储
3、计数器:常规Key-Value缓存应用,如微博数、粉丝数。INCR本身就具有原子性特性,所以不会有线程安全问题

hash

Redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects . Each hash can store 2 32 -1 key-value pairs. It can be seen as a MAP container for KEY and VALUE. Compared to JSON, hash occupies very little memory space.

Common commands

  • HSET key_name field value: Set the field and value for the specified key
  • hmset key field value[field1,value1]
  • hget key field
  • hmget key field[field1]
  • hgetall key: returns all fields and values ​​in the hash table
  • hkeys key: Get all fields of the hash table
  • hlen key: get the number of fields in the hash table-
    hdel key field [field1]: delete one or more fields in the hash table

Application scenarios

Hash的应用场景,通常用来存储一个用户信息的对象数据。
1、相比于存储对象的string类型的json串,json串修改单个属性需要将整个值取出来。而hash不需要。
2、相比于多个key-value存储对象,hash节省了很多内存空间
3、如果hash的属性值被删除完,那么hash的key也会被redis删除

list

Similar to LinkedList in Java.

Common commands

  • lpush key value1 [value2]
  • rpush key value1 [value2]
  • lpushx key value: insert the value from the left, if the list does not exist, do not operate
  • rpushx key value: insert the value from the right, if the list does not exist, do not operate
  • llen key: Get the length of the list
  • lindex key index: Get the element of the specified index
  • lrange key start stop: Get the elements in the specified range of the list
  • lpop key: remove the first element from the left
  • prop key: remove the last element of the list
  • blpop key [key1] timeout: Remove and get the first element of the list. If there are no elements in the list, the list will be blocked until the waiting timeout or the pop-up element is found
  • brpop key [key1] timeout: Remove and get the last element of the list. If there are no elements in the list, the list will be blocked until the waiting timeout or the pop-up element is found
  • ltrim key start stop: Modify the list so that the list only retains the elements in the specified interval, and the elements not in the specified interval will be deleted
  • lset key index value: the value of the specified index
  • linsert key before|after world value: insert an element before or after the list element

Application scenarios

1、对数据大的集合数据删减
		列表显示、关注列表、粉丝列表、留言评价...分页、热点新闻等
2、任务队列
		list通常用来实现一个消息队列,而且可以确保先后顺序,不必像MySQL那样通过order by来排序

supplement:

  • rpoplpush list1 list2 Remove the last element of list1, add the element to list2 and return this element
    . This command can be used to implement the order placing process, user system login and SMS registration, etc.

set

Unique, disorderly

  • sadd key value1[value2]: add members to the collection
  • scard key: returns the number of members in the collection
  • smembers key: return all members in the set
  • sismember key member: Determine whether the memeber element is a member of the set key member
  • srandmember key [count]: return one or more random numbers in the set
  • srem key member1 [member2]: Remove one or more members from the set
  • spop key: remove and return a random element in the set
  • smove source destination member: move the member element from the source collection to the destination collection
  • sdiff key1 [key2]: returns the difference of all sets
  • sdiffstore destination key1[key2]: Returns the difference of all the given sets and stores them in the destination
对两个集合间的数据[计算]进行交集、并集、差集运算
1、以非常方便的实现如共同关注、共同喜好、二度好友等功能。对上面的所有集合操作,你还可以使用不同的命令选择将结果返回给客户端还是存储到一个新的集合中。
2、利用唯一性,可以统计访问网站的所有独立 IP

zset

Orderly and not repetitive. Each element is associated with a double type score, and Redis sorts from small to large by the score. The score can be repeated

ZADD key score1 memeber1
ZCARD key: Get the number of elements
in the set
ZCOUNT key min max Calculate the number of members with a specified interval score in an ordered set ZCOUNT key min max Calculate the number of members with a specified interval score in an ordered set
ZRANK key member: return The index of the specified member of the ordered set
ZREVRANGE key start stop: Returns the member in the specified range of the ordered set, and the score is from the highest to the end through the index.
ZREM key member [member …] Remove one or more members from the ordered set.
ZREMRANGEBYRANK key start stop Remove all members of the given ranking interval in the ordered set (the first place is 0) (low to high ranking)
ZREMRANGEBYSCORE key min max Remove all members of the given score interval in the ordered set

常用于排行榜:
1、如推特可以以发表时间作为score来存储
2、存储成绩
3、还可以用zset来做带权重的队列,让重要的任务先执行

Jedis和Spring-data-redis


  1. Connect redis
@Test
public void test(){
    
    
	Jedis jedis = new Jedis("host",port);
	jedis.auth("password");
	// 操作redis
	jedis.close();
}
  1. JedisPool
// 创建config
JedisPoolConfig config = new JedisPoolConfig();
con.setMaxTotal(5);// 最大连接数
...
// 创建连接池
JedisPool pool = new JedisPool(config,host,port);
Jedis jedis = pool.getResource();
jedis.auth();
  1. Spring-data
  • Import Jedis and Spring-data-redis
  • The configuration file is as follows
    Insert picture description here
    -test connection
    Insert picture description here
  • Configure the serialization method:
    save any data in redis, it needs to be serialized, and the JdkSerializationRedisSerializer is used for serialization by default. JdkSerializationRedisSerializer will add a string of strings before all the key and value, as well as the original characters of hashkey and hashvalue.Insert picture description here

Redis features


Publish and subscribe

Redis publish and subscribe (pub/sub) is a message communication mode: the sender (pub) sends a message, and the subscriber (sub) receives the message.

Redis clients can subscribe to any number of channels.

The following figure shows the relationship between channel channel1 and the three clients that subscribe to this channel-client2, client5, and client1:
Insert picture description here
when a new message is sent to channel channel1 through the PUBLISH command, this message will be sent to subscribe to it Of the three clients:
Insert picture description here
commands

  • subscribe channel [channel...]: subscribe to one or more channels
  • psubscribe pattern [pattern...]: subscribe to one or more channels that conform to the specified pattern
  • publish channel message: send information to the specified channel
  • unsubscribe [channel[channel…]]: Unsubscribe from the channel
  • punsubscribe [pattern[pattern…]]: Unsubscribe from all channels of a given pattern

Application scenarios

构建实时的消息系统,比如普通聊天、群聊等功能。
1、博客网站订阅,当作者发布就可以推送给粉丝
2、微信公众号模式

Redis multi-database

  • select db
  • move key db
  • flushdb
  • flushall

Redis transaction

Redis transactions can execute multiple commands at once (sequentially executed in sequence, and other commands are not allowed to be inserted into the execution sequence during execution).
1. Redis will serialize all commands in a transaction, and then execute them in order.
2. During execution, they will not be inserted by other commands, and jamming is not allowed.

Insert picture description here

  1. Enter the Multi command to start, the entered commands will all enter the command queue in turn, but will not be executed
  2. Until you enter exec, Redis will execute the commands in the previous queue in sequence
    Insert picture description here
  3. discard queue execution
    Insert picture description here
  4. If a command reports an error, only the command that reports the error will not be executed, and other commands will be executed without rollback.
    Insert picture description here
  5. If a command in the queue reports an error (syntax error), the entire queue will be cancelled during execution

Master-slave replication

Redis master-slave replication configuration

Redis cluster

Redis cluster setup:
Redis documentation
Redis cluster tutorial
Redis-5.0.5
cluster setup The difference between stand-alone Redis and cluster Redis
Redis-4.0 cluster setup

Redis persistence

  1. RDB

RDB is the default persistence mechanism for Redis. RDB is equivalent to a snapshot, which saves a state

Advantages:
save speed, restore speed is extremely fast,
suitable for disaster backup
Disadvantages:
small memory machines are not suitable for use. The RDB mechanism will take a snapshot if it meets the requirements.

  1. AOF
    If Redis is accidentally down, the RDB method will lose all the changes made after the last snapshot. If the application is required to not lose any modifications, AOF persistence can be used.

AOF: Append-Only File: Redis will append every write command received to the file (the default is appendonly.aof). When Redis restarts, it will re-execute the write command in the file to rebuild the content of the entire database.

The problem that arises:
Some commands are redundant.

Guess you like

Origin blog.csdn.net/qq_42647711/article/details/104814203
Recommended