How to use Redis to solve the problem of concurrent data re-insertion into MySQL?

  question

Business scenario

There is a query system, when users query, if the database has no data, they need to call a third-party query interface to obtain the data, then insert the data into the database, and then find out the data from the database and return it to users. [The system is developed based on PHP]

Problem description

If multiple users query, there will be multiple requests to query the third-party interface at the same time, thus causing the problem of repeated data insertion.

How can this problem be solved?
When calling a third-party interface, use theRedisTo ensure that there is only one request to a third party, thus avoiding repeated queries and insertions of data, is there any other good method? How will this be achieved?
Thank you!

Locking mechanism. Check whether the operation is locked before the code enters the operation, and if so, interrupt the operation. Otherwise, proceed to the next operation, first lock the operation, then execute the code, and finally open the operation lock after executing the code. Otherwise, you will have no way to carry out the next execution.

There are many locking codes, one of which is given upstairs. Redis, memcache, cache files can be used, if the concurrent operation is relatively high, it is recommended to use the above-mentioned redis. (In fact, the string data type is used to assign a value {lock} to the lock key, and when the lock is unlocked, the value of this key will be cleared or assigned a value of 0)

$lock_status = $redis->get('lock_state');
 if ($lock_status == 0 || empty($lock_status)) {
 $redis->set('lock_state', 3600, 1);  # Operation Lock
 # Operation Code
 $redis->set('lock_state', 3600, 0);  # Operation Unlock
 } else {
 # Operation after Locking
 bracket