Redis – PHP in actual combat

public function getRedis()
{
    $redis = new \Redis();
    $redis->connect(env("REDIS_MASTER".'127.0.0.1'), 6379);$redis->auth(env('REDIS_AUTH'.'123456'));
    return $redis;
}

$redis = $this->getRedis();
Copy the code

String Simple String caching practice

$key  = 'str:name'; // String caching$redis->set($key.'WXiangQian');
$name = $redis->get($key);
echo $name; // WXiangQian
$redis->expire($strCacheKey, 30);  Set expiration to 30 seconds
Copy the code

HSET Simple hash cache combat

$key = 'hset:name'

$uid = 1;
$redis->hSet($key.$uid.'WXiangQian');
$data = $redis->hGet($key, 1);
print_r($data); // Output dataCopy the code

Leaderboard combat

$strKey = 'zset:ranking_list'; // Store data$redis->zadd($strKey.'50', json_encode(['name'= >'Tom']));
$redis->zadd($strKey.'70', json_encode(['name'= >'John']));
$redis->zadd($strKey.'90', json_encode(['name'= >'Jerry']));
$redis->zadd($strKey.'30', json_encode(['name'= >'Job']));
$redis->zadd($strKey.'100', json_encode(['name'= >'LiMing']));
 
$dataOne = $redis->ZREVRANGE($strKey, 0, 1,true);
echo "-- {$strKey} from largest to smallest ---- <br /><br />";
print_r($dataOne);
 
$dataTwo = $redis->ZRANGE($strKey, 0, 1,true);
echo "<br /><br />---- {$strKey---- <br /><br />";
print_r($dataTwo);
Copy the code

List pagination

$strKey = 'list:data';
$page = $request->input('page', 1);$pageSize = $request->input('limit', 50);$limit_s = ($page- 1) *$pageSize;
$limit_e = ($limit_s + $pageSize) - 1;
$data = $tools->redis->lRange($strKey.$limit_s.$limit_e);
print_r($data);
Copy the code

Simple string pessimistic lock combat

Explanation: The Pessimistic Lock, as the name implies, is Pessimistic.

Every time I go to get the data, I think someone else will change it, so I lock it every time I get the data.

Scenario: If caching is used in the project and a timeout is set for caching.

When the concurrency is high, if there is no locking mechanism, then the moment the cache expires,

A large number of concurrent requests can query the database directly through the cache, causing an avalanche effect.

/** * get lock * @param String$keyLock identifier * @param Int$expireLock expiration time * @return Boolean
 */
public function lock($key = ' '.$expire{= 5)$is_lock = $this->_redis->setnx($key, time()+$expire); // Cannot get lockif(!$is_lock){// Determine whether the lock has expired$lock_time = $this->_redis->get($key); // The lock has expired. Delete the lock and try againif (time() > $lock_time) {
            unlock($key);
            $is_lock = $this->_redis->setnx($key, time() + $expire); }}return $is_lock? true : false; } /** * release lock * @param String$keyLock identifier * @return Boolean
 */
public function unlock($key = ' ') {return $this->_redis->del($key); } // Define the lock identifier$key = 'str:lock'; / / acquiring a lock$is_lock = lock($key, 10);
if ($is_lock) {
    echo 'get lock success<br>';
    echo 'do sth.. 

'
; sleep(5); echo 'success<br>'; unlock($key); } else{// Failed to get the lockecho 'request too frequently<br>'; } Copy the code

Simple affairs optimistic lock actual combat

Explanation: Optimistic Lock, as the name suggests, is Optimistic.

Every time I went to pick up the data, I thought no one would change it, so I wouldn’t lock it.

The watch command will monitor the given key, and the whole transaction will fail if the monitored key has changed since the call to watch during exec.

Watch can also be called to monitor multiple keys multiple times. This allows optimistic locks to be added to the specified key.

Note that the watch key is valid for the entire connection, as are transactions.

If the connection is disconnected, both monitoring and transactions are automatically cleared.

Of course, the exec, discard, and unwatch commands remove all monitoring from the connection.

$strKey = 'str:age';
 
$redis->set($strKey, 10);$age = $redis->get($strKey);
 
echo "---- Current Age:{$age} ---- <br/><br/>"; / / 10$redis->watch($strKey); // Start the transaction$redis->multi(); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / * * * at the same time opened a new session to perform new * * redis - cli is carried out$redis->set($strKey, 30); // New session emulates other terminal * this time$age= 30; 30 * / / / / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -$redis->set($strKey, 20);$redis->exec(a);$age = $redis->get($strKey);
 
echo "---- Current Age:{$age} ---- <br/><br/>"; / / / / when 30execIf the monitored key has changed since the call to watch, the whole transaction will failCopy the code

Pessimistic locks and optimistic locks apply to the following scenarios:

Pessimistic lock: It is suitable for scenarios with frequent write operations. If a large number of read operations occur, locks will be added each time the read operations occur, which increases the overhead of locks and reduces the throughput of the system.

Optimistic lock: Applies to scenarios where read operations are frequent. If a large number of write operations occur, data conflicts are more likely. To ensure data consistency, the application layer needs to continuously obtain data, which increases a large number of query operations and reduces the throughput of the system.

Conclusion: Both methods have their advantages and disadvantages. Optimistic locks are frequently used for reading and pessimistic locks are frequently used for writing.

Such optimistic locking is suitable for low write situations, where conflicts are really rare, thus eliminating the overhead of locking and increasing the overall throughput of the system. However, if conflicts occur frequently, upper-layer applications will retry, which degrades performance. Therefore, pessimistic locks are appropriate. Pessimistic locks are used when two users have a high probability of updating the same data, that is, when conflicts are serious.

Pessimistic locking is suitable for strong consistency scenarios, but low efficiency, especially low read concurrency. Optimistic locking is suitable for scenarios with more read and less write and fewer concurrent conflicts

Redis essay collection

Redis Basics – Redis installation

Redis Basics – Introduction and Understanding

Redis Basics – Basic Usage

Redis Advancements – PHP connects to Redis

Redis-php – Common use scenarios