search
HomeDatabaseRedisHow to use Redis to solve high concurrency

NoSQL

Abbreviation for Not Only SQL. NoSQL was proposed to solve the inability of traditional RDBMS to deal with certain problems.

That is, non-relational databases. They do not guarantee the ACID characteristics of relational data. There is generally no correlation between data. They are very easy to implement in terms of expansion and have high performance.

Redis

Redis is a typical representative of nosql and is also a must-use technology for current Internet companies.

Redis mainly uses hash tables to implement key-value pair storage. Most of the time, it is used directly in the form of cache, so that the request does not directly access the disk, so the efficiency is very good, and it can fully meet the needs of small and medium-sized enterprises.

Common data types

  • String string

  • Hash hash

  • List list

  • ##sets sets

  • Ordered set sort set

String and hash are used more frequently. Each type has its own operation command, which is nothing more than adding, deleting, modifying and checking. I will sort out the specific commands later.

Pain Points

When many requests occur simultaneously in web applications, it may cause errors in data reading and storage, that is, dirty reads and dirty data generation occur.

Under distributed projects, more problems will arise.

Thoughts

When it comes to concurrency, the essence is that multiple requests come in at the same time and cannot be processed correctly.

You can put all requests in a queue, so that the requests can come in one by one in order to execute the business logic. Using message queues is currently a feasible solution. I will compile an article on how to deal with high concurrency message queues next time

Another method is to directly convert parallelism to serialization. Java provides synchronized. That is synchronization, but this is still not a suitable solution in places with strict efficiency requirements or distributed projects. This leads to the use of redis to implement distributed locks to solve concurrency problems.

Distributed lock

In distributed projects, a unique, universal, and efficient identifier is used to represent locking and unlocking.

Redis is very simple to implement, that is, whether a key exists or not indicates whether it is locked or unlocked.

Take the string type as an example:

Integer stock = goodsMapper.getStock();
if (stock > 0) {
    stock =- 1;
    goodsMapper.updateStock(stock);
}

The above is the simplest pseudo code for instant killing. We try to use redis to implement distributed locks.

// 这里是错误代码,只是一个思考过程,请耐心看完哦
String key = "REDIS_DISTRIBUTION_LOCKER"; // 分布式锁名称
String value = jedisUtils.get(key);
if (value != null) { // 未上锁
    // wingzingliu
    jedisUtils.set(key, 1); // 上锁
    Integer stock = goodsMapper.getStock();
    if (stock > 0) {
        stock =- 1;
        goodsMapper.updateStock(stock);
        jedisUtils.del(key); // 释放锁
    }
}

There may be a problem with the above code, that is, when multiple requests come in at the same time, and multiple requests at a certain time all get the value as empty, thread A enters the if and goes to // wingzingliu. Locking, other requests also come in, so dirty data will appear.

The code problem here is that the atomicity issue is not considered.

So we have to use a setNx command of redis. The essence is to set the value, but this is an atomic operation. After execution, it will return whether the setting is successful.

redis> SETNX job "programmer"    # job 设置成功
(integer) 1
 
redis> SETNX job "code-farmer"   # 尝试覆盖 job ,失败
(integer) 0
 
redis> GET job                   # 没有被覆盖
"programmer"

Focus on when there is a value, it will fail and return 0. So our code will be transformed into the following.

// 这里是错误代码,只是一个思考过程,请耐心看完哦
String key = "REDIS_DISTRIBUTION_LOCKER"; // 分布式锁名称
Long result = jedisUtils.setNx(key, 1);
if (result > 0) { // 上锁成功,进入逻辑
    // wingzingliu1
    Integer stock = goodsMapper.getStock();
    if (stock > 0) {
        stock =- 1;
        goodsMapper.updateStock(stock);
 
        System.out.println("购买成功!");
    } else {
        System.out.println("没有库存了!");
    }
    // wingzingliu2
    jedisUtils.del(key); // 释放锁
}

With the above, we can ensure atomicity and process them correctly in order.

But there is another hidden problem, that is, after a thread successfully executes the lock, the program throws an exception between wingzingliu1 and wingzingliu2. Then the program terminates and the lock cannot be released. Other threads They can't even get in.

The solution is to add a try catch finally block and release the lock in finally.

But what if it is down? After the lock is locked, the machine crashes. The finally contents will still not be executed. The lock is not released. Without manual processing, all threads will not be able to enter in the future.

So the expiration time of redis is introduced, and it will be automatically unlocked at a certain time.

// 这里是不够完善的代码,请耐心看完哦
try {
    String key = "REDIS_DISTRIBUTION_LOCKER"; // 分布式锁名称
    Long result = jedisUtils.setNx(key, 1, 30); // 假设处理逻辑需要20s左右,设置了30秒自动过期
    if (result > 0) { // 上锁成功,进入逻辑
        Integer stock = goodsMapper.getStock();
        if (stock > 0) {
            stock =- 1;
            goodsMapper.updateStock(stock);
 
            System.out.println("购买成功!");
        } else {
            System.out.println("没有库存了!");
        }
    }
} catch (Exception e) {
    
} finally {
    jedisUtils.del(key); // 释放锁
}

The above is a relatively complete distributed lock, but there is still a small flaw. It is assumed that a certain request A is processed very slowly. It is expected to take 20s but it takes 35s. When it reaches 30s, the lock expires. Other requests came naturally.

This will not only cause a concurrent execution, but also continue to perform the lock release operation after request A is processed, thus actually handing the lock to the next thread. By analogy, the entire concurrency control will be messed up.

Theoretically, you can set a larger key expiration time, but it is not the best solution. Here comes a concept: locking life.

Lock life extension

As the name suggests, give the lock life extension. The implementation is to extend the lock time when the lock is about to expire. Assume a 30 second lock is used, with a check every 10 seconds to see if the lock still exists. If the lock still exists, keep the lock for 30 seconds. This avoids the possible problem above.

A scheduled task is used here and can be called periodically.

Extension

The value just set for the key is 1. In fact, the request ID can be used to save it, so that you can know which request the lock is from, and you can avoid it when unlocking. Locks on other threads are unlocked. It can be passed by the front end, or generated by the server based on certain rules.

The above is the detailed content of How to use Redis to solve high concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
es和redis区别es和redis区别Jul 06, 2019 pm 01:45 PM

Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

一起来聊聊Redis有什么优势和特点一起来聊聊Redis有什么优势和特点May 16, 2022 pm 06:04 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

实例详解Redis Cluster集群收缩主从节点实例详解Redis Cluster集群收缩主从节点Apr 21, 2022 pm 06:23 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

Redis实现排行榜及相同积分按时间排序功能的实现Redis实现排行榜及相同积分按时间排序功能的实现Aug 22, 2022 pm 05:51 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

详细解析Redis中命令的原子性详细解析Redis中命令的原子性Jun 01, 2022 am 11:58 AM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

实例详解Redis实现排行榜及相同积分按时间排序功能的实现实例详解Redis实现排行榜及相同积分按时间排序功能的实现Aug 26, 2022 pm 02:09 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

一文搞懂redis的bitmap一文搞懂redis的bitmapApr 27, 2022 pm 07:48 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

redis error什么意思redis error什么意思Jun 17, 2019 am 11:07 AM

redis error就是redis数据库和其组合使用的部件出现错误,这个出现的错误有很多种,例如Redis被配置为保存数据库快照,但它不能持久化到硬盘,用来修改集合数据的命令不能用。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools