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

What are the common usage scenarios of using PHP to use Redis

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly shows you "what are the common use scenarios of using PHP to use Redis", the content is simple and clear, and I hope it can help you solve your doubts, so let me lead you to study and learn about "what are the common usage scenarios of using PHP to use Redis".

Simple string caching in practice

$redis- > connect ('127.0.0.1 dollars, 6379); $strCacheKey =' Test_bihu'; / / SET Application $arrCacheData = ['name' = >' job', 'sex' = >' male', 'age' = >' 30']; $redis- > set ($strCacheKey, json_encode ($arrCacheData); $redis- > expire ($strCacheKey, 30); # Expiration after 30 seconds $json_data = $redis- > get ($strCacheKey); $data = json_decode ($json_data); print_r ($data- > age) / / output data / / HSET application $arrWebSite = ['google' = > [' google.com', 'google.com.hk'],]; $redis- > hSet ($strCacheKey,' google', json_encode ($arrWebSite ['google'])); $json_data = $redis- > hGet ($strCacheKey,' google'); $data = json_decode ($json_data); print_r ($data); / / output data

Simple queue actual combat

$redis- > connect (,); $strQueueName =; $redis- > rpush ($strQueueName, json_encode ([= >, = >])); $redis- > rpush ($strQueueName, json_encode ([= >, = >])); $redis- > rpush ($strQueueName, json_encode ([= >, = >])); $strCount = $redis- > lrange ($strQueueName,); print_r ($strCount); $redis- > lpop ($strQueueName); $strCount = $redis- > lrange ($strQueueName,); print_r ($strCount)

Simple publish and subscribe practice

/ / the following are the contents of the pub.php file: run ini_set ('default_socket_timeout',-1) under cli; $redis- > connect (' 127.0.0.1 redis-, 6379); $strChannel = 'Test_bihu_channel'; / / publish $redis- > publish ($strChannel, "push from {$strChannel} channel"); echo "- {$strChannel}-channel message pushed successfully ~"; $redis- > close () / / the following is the content of sub.php file running ini_set ('default_socket_timeout',-1) under cli; $redis- > connect (' 127.0.0.1 subscription, 6379); $strChannel = 'Test_bihu_channel'; / / subscribe to echo'-subscribe to {$strChannel} this channel and wait for the message to be pushed.-"; $redis- > subscribe ([$strChannel], 'callBackFun') Function callBackFun ($redis, $channel, $msg) {print_r (['redis' = > $redis,' channel' = > $channel, 'msg' = > $msg]);}

Simple counter actual combat

$redis- > connect ('127.0.0.1 dollars, 6379); $strKey =' Test_bihu_comments'; / / set the initial value $redis- > set ($strKey, 0); $redis- > INCR ($strKey); / / + 1$ strNowCount = $redis- > get ($strKey); echo "- the current quantity is {$strNowCount}.--"

The ranking list is practical.

$redis- > connect (,); $strKey =; $redis- > zadd ($strKey, json_encode ([= >])); $redis- > zadd ($strKey, json_encode ([= >])); $redis- > zadd ($strKey, json_encode ([= >])); $redis- > zadd ($strKey, json_encode ([= >])); $redis- > zadd ($strKey, json_encode ([= >])); $dataOne = $redis- > ZREVRANGE ($strKey,); print_r ($dataOne) $dataTwo = $redis- > ZRANGE ($strKey,); print_r ($dataTwo)

Simple string pessimistic lock actual combat

Explanation: pessimistic lock (Pessimistic Lock), as the name implies, is very pessimistic.

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

Scenario: if the cache is used in the project and the timeout is set for the cache.

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

A large number of concurrent requests will penetrate the cache and query the database directly, resulting in an avalanche effect.

/ * * acquire lock * @ param String $key lock ID * @ param Int $expire lock expiration time * @ return Boolean * / public function lock ($key ='', $expire = 5) {$is_lock = $this- > _ redis- > setnx ($key, time () + $expire); / / cannot acquire lock if (! $is_lock) {/ / determine whether the lock expires $lock_time = $this- > _ redis- > get ($key) / / the lock has expired. Delete the lock and reacquire if (time () > $lock_time) {unlock ($key); $is_lock = $this- > _ redis- > setnx ($key, time () + $expire);}} return $is_lock? True: false;} / * release lock * @ param String $key lock ID * @ return Boolean * / public function unlock ($key =') {return $this- > _ redis- > del ($key);} / / define lock ID $key = 'Test_bihu_lock'; / / acquire lock $is_lock = lock ($key, 10); if ($is_lock) {echo' get lock success

'; echo' do sth..

'; sleep (5); echo' success

'; unlock ($key);} else {/ / failed to acquire lock echo' request too frequently

';}

The optimistic lock of simple affairs

Explanation: optimistic lock (Optimistic Lock), as its name implies, is optimistic.

Every time I go to get the data, I think that others will not change it, so it will not be locked.

The watch command monitors a given key, and if the monitored key has changed since watch was called during exec, the entire transaction will fail.

You can also call watch to monitor multiple key multiple times. This allows you to add an optimistic lock to the specified key.

Note that the key of watch is valid for the entire connection, as is the transaction.

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

Of course, the exec,discard,unwatch command clears all monitoring from the connection.

$strKey = 'Test_bihu_age';$redis- > set ($strKey,10); $age = $redis- > get ($strKey); echo "- Current Age: {$age} -"; $redis- > watch ($strKey); / / Open transaction $redis- > multi (); / / when a new session is opened, execute $redis- > set ($strKey,30); / / New session echo "- Current Age: {$age} -" / / 30$ redis- > set ($strKey,20); $redis- > exec (); $age = $redis- > get ($strKey); echo "- Current Age: {$age} -"; / 30 / / if the monitored key has changed since the call to watch, the whole transaction will fail. Thank you for reading all of the article "what are the common usage scenarios for using PHP to use Redis"? I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Internet Technology

Wechat

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

12
Report