Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Basic application of Redis

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Basic Application of Redis (1)

=

Overview:

Introduction, functions and advantages of Redis and comparison with other key-value databases

Installation and program environment of Redis

Command line client command

Data structure of Redis

=

Introduction to Redis

1. Brief introduction

★ Redis

REmote DIctionary Server (Redis) is a key-value storage system written by Salvatore Sanfilippo.

Redis is an open source log database written in ANSI C language, complies with BSD protocol, supports network, can be memory-based and persistent, Key-Value database, and provides API in multiple languages.

It is often called a data structure server because the value can be of types such as String, Map, list, sets, and sorted sets.

☉ REmote DIctionary Server (Redis)

Memory storage

Persistence

Principal and subordinate

Cluster

☉ Redis and other key-value cache products have the following three features:

Redis supports data persistence. You can save the data in memory on disk and load it again when you restart it.

Redis not only supports simple key-value type data, but also provides storage of data structures such as list,set,zset,hash.

Redis supports data backup, that is, data backup in master-slave mode.

two。 Function

The features supported by ★ are as follows:

☉ data structure server:

Values (value) can be strings (String), hashes (Map), lists (list), sets (sets), and ordered sets (sorted sets), and so on.

☉ single process

CPU is not a bottleneck

☉ persistence mechanism

Snapshoting

AOF

☉ Replication

Master and slave:

Master: rw

From: read-only

3. advantage

★ advantage

Extremely high performance-Redis can read at a speed of 110000 times per second and write at a speed of 81000 times per second.

Rich data types-Redis supports Strings, Lists, Hashes, Sets and Ordered Sets data type operations for binary cases

Atom-all operations of Redis are atomic, and Redis also supports atomicity after several operations have been merged.

Rich features-Redis also supports publish/subscribe, notification, key expiration, and so on.

What is the difference between 4.Redis and other key-value stores

★ differences:

Redis has more complex data structures and provides atomic operations on them, which is an evolutionary path different from other databases. The data types of Redis are based on basic data structures while being transparent to programmers without additional abstraction.

Redis runs in memory but can be persisted to disk, so memory needs to be weighed when reading and writing high-speed data sets, because the amount of data cannot be larger than hardware memory. Another advantage of in-memory databases is that compared to the same complex data structures on disk, it is very easy to operate in memory, so Redis can do a lot of things with strong internal complexity. At the same time, they are compact and appended in terms of disk format, because they do not need random access.

The difference between ★ and memcached

Redis not only supports simple KBE data, but also provides storage of data structures such as list,set,hash. Memcache only supports string values (stream data)

Redis is single-threaded and Memcached is multithreaded, but the performance is comparable.

Redis supports data backup, that is, data backup in master-slave mode.

Redis supports data persistence, which can keep the data in memory on disk and can be loaded and used again when rebooting. In Redis, not all data is stored in memory all the time. This is the biggest difference compared with Memcached)

Application scenarios are different: Redis can be used not only as a NoSQL database, but also as message queues, data stacks and data caches; Memcached is suitable for caching SQL statements, data sets, user temporary data, deferred query data and session.

Comparison of ★ redis, memcache and mongoDB

Redis, memcache and mongoDB are compared from the following dimensions. Welcome to clap bricks.

☉ performance

All of them are relatively high, and performance should not be a bottleneck for us.

Generally speaking, in terms of TPS, redis is similar to memcache, but larger than mongodb.

Convenience of ☉ operation

Memcache data structure is single

Redis is richer. In terms of data operation, redis is better and has fewer network IO times.

Mongodb supports rich data expression, index, most similar to relational database, and supports a wide range of query languages.

The size of ☉ memory space and the amount of data

Redis adds its own VM feature after version 2.0, which breaks through the limitation of physical memory; you can set the expiration time of key value (similar to memcache)

Memcache can modify the maximum available memory, using LRU algorithm

MongoDB is suitable for large amount of data storage, relying on the operating system VM for memory management, eating memory is also relatively strong, services should not be together with other services.

☉ availability (single point of issue)

For a single point problem

Redis relies on the client to achieve distributed read and write; in master-slave replication, every time the slave node reconnects to the master node, it depends on the entire snapshot, no incremental replication, due to performance and efficiency problems.

Therefore, the single point problem is more complex; does not support automatic sharding, we need to rely on the program to set a consistent hash mechanism.

One alternative is to use your own active replication (multiple copies of storage) without redis's own replication mechanism, or change to incremental replication (which needs to be implemented by yourself), a tradeoff between consistency and performance

Memcache itself has no data redundancy mechanism and is not necessary. For fault prevention, we use mature hash or ring algorithm to solve the jitter problem caused by single point of failure.

MongoDB supports master-slave,replicaset (internal paxos election algorithm, automatic fault recovery), auto sharding mechanism, and shields the client from the failover and segmentation mechanism.

☉ reliability (persistence)

For data persistence and data recovery

Redis support (snapshot, AOF): relying on snapshots for persistence, aof enhances reliability while affecting performance

Memcache does not support it and is usually used for caching to improve performance.

MongoDB has adopted binlog since version 1.8 to support the reliability of persistence.

☉ data consistency (transaction support)

Memcache uses cas to ensure consistency in concurrent scenarios

Redis transaction support is relatively weak, so it can only guarantee the continuous execution of each operation in the transaction.

MongoDB does not support transactions

☉ data analysis

MongoDB has built-in data analysis function (mapreduce), which is not supported by others.

☉ application scenario

Redis: more performance operations and operations with small amounts of data

Memcache: used to reduce database load and improve performance in dynamic systems; cache to improve performance (suitable for reading more and writing less; for large amounts of data, sharding can be used)

MongoDB: mainly solve the problem of access efficiency of massive data

Redis installation and data structure

1. Installation and program environment

★ installation method:

Compilation and installation

Rpm package installation

★ program environment

☉ profile

/ etc/redis.conf

/ etc/redis-sentinel.conf

☉ main program

/ usr/bin/redis-server

/ usr/bin/redis-sentinel

Listening port: 6379/tcp

☉ command line client

/ usr/bin/redis-cli

Demo:

1. Install the package

# configure epel warehouse [root@centos7 ~] # yum install redis

two。 The program environment is as follows:

[root@centos7 ~] # rpm-ql redis/etc/logrotate.d/redis/etc/redis-sentinel.conf/etc/redis.conf/etc/systemd/system/redis-sentinel.service.d/etc/systemd/system/redis-sentinel.service.d/limit.conf/etc/systemd/system/redis.service.d/etc/systemd/system/redis.service.d/limit.conf/usr/bin/redis-benchmark/usr/bin/redis-check-aof/usr/bin/redis-check- Rdb/usr/bin/redis-cli/usr/bin/redis-sentinel/usr/bin/redis-server/usr/bin/redis-shutdown/usr/lib/systemd/system/redis-sentinel.service/usr/lib/systemd/system/redis.service/usr/lib/tmpfiles.d/redis.conf/usr/share/doc/redis-3.2.3/usr/share/doc/redis-3.2.3/00-RELEASENOTES/usr/share/doc/redis-3.2.3/BUGS/ Usr/share/doc/redis-3.2.3/CONTRIBUTING/usr/share/doc/redis-3.2.3/MANIFESTO/usr/share/doc/redis-3.2.3/README.md/usr/share/licenses/redis-3.2.3/usr/share/licenses/redis-3.2.3/COPYING/var/lib/redis/var/log/redis/var/run/redis

3. The configuration file / etc/redis.conf is as follows:

# backup [root@centos7 ~] # cp / etc/redis.conf { .bak} [root@centos7 ~] # grep "^ # #" / etc/redis.conf## INCLUDES # # NETWORK # GENERAL # # # # SNAPSHOTTING # REPLICATION # # SECURITY # LIMITS # # APPEND ONLY MODE # # LUA SCRIPTING # REDIS CLUSTER # # # SLOW LOG # LATENCY MONITOR # # # # EVENT NOTIFICATION # ADVANCED CONFIG # # [root@centos7 ~] # vim / etc/redis.conf bind 0.0.0.0 # modify bound port # start redis Check the sturdy port 6379 [root@centos7 ~] # systemctl start redis [root@centos7 ~] # ss-tnlp | grep "redis" LISTEN 0128 *: 6379 *: * users: ("redis-server", pid=3840,fd=4))

3. Command line client command

★ redis-cli

☉ syntax:

Redis-cli [OPTIONS] [cmd [arg [arg...]

Common options for ☉:

-h Server hostname (default: 127.0.0.1). / / Host address

-p Server port (default: 6379). / / Port

-a Password to use when connecting to the server. / / password

Demo:

1. To connect locally, just run the redis-cli command directly

[root@centos7 ~] # redis-cli127.0.0.1:6379 > pingPONG

two。 Remote connection, indicating the host, port and password to connect to

[root@centos7 ~] # redis-cli-h 192.168.1.112198.1.112redis-cli 3.2.3To get help about Redis commands type > pingPONG192.168.1.112:6379 > help # get help redis-cli 3.2.3To get help about Redis commands type: "help @" to get a list of commands in "help" for help on "help" to get a list of possible help topics "quit" to exitTo set redis-cli perferences: ": set hints" enable online Hints ": set nohints" disable online hintsSet your preferences in ~ / .redisclircRedis:k/v

1.k/v and group

★ k/v

Key: direct ASCII string

Value (data structure): string,lists,hashes,set,sored sets,bltmaps,hyperloglog

★ group

@ string,@generic,@list @...

2.string (string)

★ function:

Commands related to the Redis string data type are used to manage redis string values

Basic ☉ syntax:

127.0.0.1 purl 6379 > COMMAND KEY_NAME

Demo:

192.168.1.112 INCR count 6379 > SET count 1OK192.168.1.112:6379 > GET count "1" 192.168.1.112 INCR count 6379 > INCR count (integer) 3192.168.1.112 12 INCR count 6379 > INCR count (integer) 4192.168.1.112 126379 > INCR count (integer) 5192.168.1.112 12 DECR count 6379 > DECR count (integer) 4192.168.1.112 12 DECR count 6379 > DECR count (integer) 3192.168.1.112 12 DECR count > DECR count (integer) 2192.168.1.112 integer 6379 > DECR count (integer) 1

The following table lists the commonly used redis string commands:

Serial number command and description 1SET key value

Sets the value 2GET key of the specified key

Gets the value of the specified key. 3GETRANGE key start end

Returns the subcharacter 4GETSET key value of the string value in key

Sets the value of the given key to value and returns the old value of key (old value). 5GETBIT key offset

Gets the bit (bit) at the specified offset for the string value stored by key. 6MGET key1 [key2..]

Gets all (one or more) values of a given key. 7SETBIT key offset value

Sets or clears the bit (bit) on the specified offset for the string value stored by key. 8SETEX key seconds value

Associate the value value to key and set the expiration time of key to seconds (in seconds). 9SETNX key value

The value of key is set only if key does not exist. 10SETRANGE key offset value

Overwrites the string value stored in a given key with the value parameter, starting with the offset offset. 11STRLEN key

Returns the length of the string value stored by key. 12MSET key value [key value...]

Set one or more key-value pairs simultaneously. 13MSETNX key value [key value...]

Set one or more key-value pairs at the same time if and only if none of the given key exists. 14PSETEX key milliseconds value

This command is similar to the SETEX command, but it sets the lifetime of the key in milliseconds, rather than seconds, as the SETEX command does. 15INCR key

Increments the numerical value stored in key by one. 16INCRBY key increment

Adds the value stored by key to the given incremental value (increment). 17INCRBYFLOAT key increment

Adds the value stored by key to the given floating-point increment value (increment). 18DECR key

Subtracts the numeric value stored in key by one. 19DECRBY key decrement

The value stored by the key minus the given decrement. 20APPEND key value

If key already exists and is a string, the APPEND command appends value to the end of the original value of key.

3.list (list)

★ action

The Redis list is a simple list of strings sorted in the order in which they are inserted. You can add a header (left) or tail (right) of the element guide list.

A list can contain up to 232-1 elements (4294967295, each list has more than 4 billion elements).

Demo:

192.168.1.112 RPUSH mylist "mon" (integer) 1192.168.1.112 12 LINDEX mylist 6379 > LINDEX mylist 0 "mon" 192.168.1.112 12 LINDEX mylist 6379 > RPUSH mylist "tun" (integer) 2192.168.1.112 > LPUSH mylist "sun" (integer) 3192.168.1.1126379 > LINDEX mylist 0 "sun" 192.168.1.11212 LINDEX mylist 6379 > LINDEX mylist 0 "sun" 192.168.1.11215 > LINDEX mylist 1 "mon" 192.168.1.112 LINDEX mylist 2 "tun" 192.168.1.112 RPOP mylist "tun" 192.168.1.112 tun 6379 > LLEN mylist (integer) 2

The following table lists the list-related basic commands:

Serial number command and description 1BLPOP key1 [key2] timeout

Move out and get the first element of the list, and if there are no elements in the list, it blocks the list until the wait times out or until a popup element is found. 2BRPOP key1 [key2] timeout

Move out and get the last element of the list, and if there are no elements in the list, it blocks the list until the wait times out or until a popup element is found. 3BRPOPLPUSH source destination timeout

Pop a value from the list, insert the pop-up element into another list and return it; if there are no elements in the list, it blocks the list until the wait times out or until a popup element is found. 4LINDEX key index

Get the element 5LINSERT key BEFORE in the list through the index | AFTER pivot value

Insert the element 6LLEN key before or after the element of the list

Get list length 7LPOP key

Remove and get the first element of the list, 8LPUSH key value1 [value2]

Insert one or more values into the list header 9LPUSHX key value

Insert one or more values into the existing list header 10LRANGE key start stop

Gets the element 11LREM key count value within the specified range of the list

Remove list element 12LSET key index value

Set the value 13LTRIM key start stop of the list element through the index

Trim a list, that is, let the list retain only the elements within the specified range, and all elements that are not within the specified range will be deleted. 14RPOP key

Remove and get the last element 15RPOPLPUSH source destination in the list

Remove the last element of the list, add that element to another list and return 16RPUSH key value1 [value2]

Add one or more values 17RPUSHX key value to the list

Add values to an existing list

4.set (collection)

★ function:

The Set of Redis is an unordered collection of type string. Collection members are unique, which means that there can be no duplicate data in the collection.

Collections in Redis are implemented through hash tables, so the complexity of adding, deleting and searching is O (1).

The maximum number of members in the collection is 4294967295 (each collection can store more than 4 billion members).

Demo:

192.168.1.112 (integer) 3192.168.1.112 (integer) 3192.168.1.112 (SMEMBERS s11) "c" 2) "b" 3) "a" 192.168.1.112 (integer) 1192.168.1.112 (integer) 6379 > SISMEMBER s1 'd' (integer) 0192.168.1.112 C 'd'f' (integer) 4192.168.1.112 SINTER S1 s21) "c" 2) a "192.168.1.112 SUNION S1 s21)" f "2)" a "3)" b "4)" d "5)" c "

The following table lists the basic Redis collection commands:

Serial number command and description 1SADD key member1 [member2]

Add one or more member 2SCARD key to the collection

Get the number of members of the collection 3SDIFF key1 [key2]

Returns the difference 4SDIFFSTORE destination key1 of a given set [key2]

Returns the difference of all given sets and stores them in destination 5SINTER key1 [key2]

Returns the intersection 6SINTERSTORE destination key1 [key2] of all given collections

Returns the intersection of all given collections and stores them in destination 7SISMEMBER key member

Determine whether the member element is a member of the collection key 8SMEMBERS key

Returns all members of the collection 9SMOVE source destination member

Move member elements from the source collection to the destination collection 10SPOP key

Removes and returns a random element in the collection 11SRANDMEMBER key [count]

Returns one or more random numbers in the collection 12SREM key member1 [member2]

Remove one or more members of the collection 13SUNION key1 [key2]

Returns the union 14SUNIONSTORE destination key1 of all given collections [key2]

The union of all given collections is stored in the destination collection 15SSCAN key cursor [MATCH pattern] [COUNT count]

Iterate over the elements in a collection

5.hash (hash)

★ function:

Redis hash is a mapping table for field and value of type string, and hash is particularly suitable for storing objects.

Each hash in Redis can store 232-1 key-value pairs (more than 4 billion).

Demo:

192.168.1.112 HSET name taotao (integer) 1192.168.1.112 HSET 6379 > HSET H2 age 25 (integer) 1192.168.1.112 12 age 6379 > HGETALL h21) "name" 2) "taotao" 3) "age" 4) "25" 192.168.1.1126379 > HKEYS H21) "name" 2) "age" 192.168.1.1126379 > HVALS H21) "taotao" 2) 25 "192.168.1.1126379 > HGET" H2 name "taotao" 192.168.1.112 HGET H2 age "25"

The following table lists the basic related commands for redis hash:

Serial number command and description 1HDEL key field2 [field2]

Delete one or more hash table fields 2HEXISTS key field

Check whether the specified field exists in the hash table key. 3HGET key field

Gets the value of the specified field stored in the hash table. 4HGETALL key

Gets all the fields and values 5HINCRBY key field increment of the specified key in the hash table

Adds an incremental increment to the integer value of the specified field in the hash table key. 6HINCRBYFLOAT key field increment

Adds an incremental increment to the floating-point value of the specified field in the hash table key. 7HKEYS key

Get the field 8HLEN key in all the hash tables

Get the number of fields in the hash table 9HMGET key field1 [field2]

Get the value of all given fields 10HMSET key field1 value1 [field2 value2]

Multiple field-value (field-value) pairs are set to the hash table key at the same time. 11HSET key field value

Set the value of field field in the hash table key to value. 12HSETNX key field value

Set the value of the hash table field only if the field field does not exist. 13HVALS key

Get all the values in the hash table 14HSCAN key cursor [MATCH pattern] [COUNT count]

Key-value pairs in an iterative hash table.

6.sorted set (ordered set)

★ function:

Redis ordered collections, like collections, are collections of elements of type string, and duplicate members are not allowed.

The difference is that each element is associated with a score of type double. Redis sorts the members of the collection from small to large by scores.

The members of an ordered set are unique, but the score can be repeated.

The collection is implemented through a hash table, so the complexity of adding, deleting, and finding is all O (1). The maximum number of members in the collection is 4294967295 (each collection can store more than 4 billion members).

The following table lists the basic commands for redis ordered collections:

Serial number command and description 1ZADD key score1 member1 [score2 member2]

Add one or more members to an ordered collection, or update the score 2ZCARD key of an existing member

Get the number of members of an ordered set 3ZCOUNT key min max

Calculate the number of members 4ZINCRBY key increment member of a specified interval score in an ordered set

Add an incremental increment5ZINTERSTORE destination numkeys key [key...] to the score of a specified member in an ordered set

Calculates the intersection of one or more given ordered sets and stores the result set in the new ordered set key 6ZLEXCOUNT key min max

Calculate the number of members in a specified dictionary interval in an ordered set 7ZRANGE key start stop [WITHSCORES]

Return the ordered set through the index interval to synthesize the member 8ZRANGEBYLEX key min max [LIMIT offset count] in the specified interval.

Returns the members of an ordered set 9ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] through a dictionary interval

Returns the member 10ZRANK key member in the specified interval of the ordered set by score

Returns the index 11ZREM key member [member...] of the specified member in an ordered collection.

Remove one or more member 12ZREMRANGEBYLEX key min max from an ordered set

Removes all member 13ZREMRANGEBYRANK key start stop of a given dictionary interval in an ordered set

Remove all members of the 14ZREMRANGEBYSCORE key min max of a given ranking interval in an ordered set

Remove all members of a given fractional interval in an ordered set 15ZREVRANGE key start stop [WITHSCORES]

Returns the members of the specified interval in the ordered set, with the score from high to 16ZREVRANGEBYSCORE key max min [WITHSCORES] by index.

Returns the members within the specified score range in an ordered set, sorted from high to low, 17ZREVRANK key member

Returns the ranking of the specified members in an ordered set, which is sorted 18ZSCORE key member by descending score (from largest to smallest)

Returns the member's score value 19ZUNIONSTORE destination numkeys key [key...] in an ordered set.

Compute the union of one or more given ordered sets and store them in the new key 20ZSCAN key cursor [MATCH pattern] [COUNT count]

Elements in an iterative ordered set (including element members and element scores)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report