search
HomeDatabaseRedisWhere is redis used?

Where is redis used?

Jun 25, 2019 am 11:45 AM
redis

Where is redis used?

1. High concurrency cache/shared session:

UserInfo getUserInfo (long id) {}

Get:

userRedisKey = "user:info:" id;

value = redis.get(userRedisKey);

if (value != null) {

userInfo = deserialize(value);

                                                                                                                                                    return userInfo;

redis.setex(userRedisKey, 3600, serialize(userInfo));

Using string to store serialized data is not three-dimensional and intuitive enough. It can be converted to hmset and stored as a hash structure, making access more intuitive.

2. Simple distributed lock

setnx can only be set successfully if it does not exist, and the rest can only wait. Single thread

3. Counter incr, because it is single-threaded, consumes less CPU than cas, etc., and has higher performance

long incrVideoCounter ( long id) {

          key = "video:playCount:" id;

4. Implement stack/queue

Stack: lpush lpop

Queue: lpush rpop

5. Flow control/rate limit

phoneNum = "12345678999"; key = "shortMsg:limit:" phoneNum;

isExists = redis.set( key, 1, "EX 60", "NX");

if (isExists != null || redis.incr(key)

// Pass

##} else {

// Do not pass

}

6.

Use lpush brpop to implement a blocking queue. The producer inserts elements from the left end of the list through lpush, and multiple consumers block and obtain the tail elements of the queue from the right end of the brpop

7. Every A user has his own articles. Now he wants to display the article list in pages.

hmset article:1 title xx context XXXX

lpush user:1:articles srticle:1 articles:3

articles = lrange user:1:articles 0 9

for article in {articles} hgetall {article}

8. Follow and like

Like: zincrby user:ranking:2016_03_15 mike 1

Cancel: zrem user:ranking:2016_03_15 mike

Get like The top 10 users: zrevrangebyrank user:ranking:2016_03_15 0 9

Display user information and scores: hgetall user:info:tom / zscore user:ranking:2016_03_15 mike / zrank user:ranking:2016_03_15 mike

9. Bitmaps calculate the relationships among big data sets

10. Ranking

mike uploaded a video and received 3 likes zadd user:ranking:2016_03_15 mike 3

Another person liked it zincrby user:ranking:2016_03_15 mike 1

11. Follow together

Add a follow tag to the user sadd user:1:tags tag1 tag2

Add a user to the tag sadd tag1:uses user:1

Common attention sinter user:1:tags user:2:tags sinter/sunion/sdiff

12. Publish and subscribe

Subscribe video:changes: publish video:changeds "video1,video2"

for video in video1,video2

update (video)

Each data type corresponds to a variety of underlying data structure implementations (object encoding), which can be switched through data size, length, scenarios, etc. to achieve higher efficiency

Persistent RDB (child process creation, binary file, fast recovery, not real-time enough)/AOF (appendonly. Text files, real-time writing operations first aop_buffer, and then write to the disk by configuring the write disk interval, and merge when reaching a certain size)

Batch hmget and other operations must be converted to hscan and other progressive traversal methods, otherwise it is easy to blockBuffering: client buffering (input/output), copy backlog buffer, aof buffer

Copy: full/incremental copy offset/copy backlog buffer (write command is sent to the slave server at the same time It also maintains a first-in-first-out queue, which means that the main service also saves the most recently propagated commands)/ID

sentinal: To achieve high availability, it is a special redis node. You can configure the cluster yourself and monitor the redis data cluster through heartbeat and other mechanisms. When a node fails and becomes unavailable, it can be discovered in time and automatically migrated

cluster: Distributed cluster, fault-tolerant leader selection, etc. Mapping physical nodes to 16383 slots to achieve dynamics

For more Redis-related technical articles, please visit the Redis Tutorial column to learn!

The above is the detailed content of Where is redis used?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Redis vs databases: performance comparisonsRedis vs databases: performance comparisonsMay 14, 2025 am 12:11 AM

Redisoutperformstraditionaldatabasesinspeedforread/writeoperationsduetoitsin-memorynature,whiletraditionaldatabasesexcelincomplexqueriesanddataintegrity.1)Redisisidealforreal-timeanalyticsandcaching,offeringphenomenalperformance.2)Traditionaldatabase

When Should I Use Redis Instead of a Traditional Database?When Should I Use Redis Instead of a Traditional Database?May 13, 2025 pm 04:01 PM

UseRedisinsteadofatraditionaldatabasewhenyourapplicationrequiresspeedandreal-timedataprocessing,suchasforcaching,sessionmanagement,orreal-timeanalytics.Redisexcelsin:1)Caching,reducingloadonprimarydatabases;2)Sessionmanagement,simplifyingdatahandling

Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.