In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the common use scenarios of Redis". In daily operation, I believe many people have doubts about the common use scenarios of Redis. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the questions of "what are the common use scenarios of Redis?" Next, please follow the editor to study!
Redis is an open source API that is written in ANSI C language, supports the network, can be memory-based and persistent, and provides API in multiple languages.
This article mainly introduces the actual combat of PHP under the common application scenarios of Redis.
Simple string caching in practice
$redis- > connect ('127.0.0.1 job', 6379); $strCacheKey =' Test_bihu';//SET App $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 ('127.0.0.1 redis-, 6379); $strQueueName =' Test_bihu_queue';// queued $redis- > rpush ($strQueueName, json_encode (['uid' = > 1 Job' name' = > Job'])); $redis- > rpush ($strQueueName, json_encode (['uid' = > 2 camera name = >' Tom'])); $redis- > rpush ($strQueueName, json_encode (['uid' = > 3 camera name' = > John']) Echo "- queue successfully; / / View queue $strCount = $redis- > lrange ($strQueueName, 0,-1); echo" current queue data is: "; print_r ($strCount); / / out queue $redis- > lpop ($strQueueName); echo"-out queue success-"; / / View queue $strCount = $redis- > lrange ($strQueueName, 0,-1); echo" current queue data is: " 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 launch, 6379); $strChannel = 'Test_bihu_channel';// release $redis- > publish ($strChannel, "push from {$strChannel} channel"); echo "- {$strChannel}-channel message pushed successfully ~"; $redis- > close () / / the following is the contents of the sub.php file running ini_set ('default_socket_timeout',-1) under cli; $redis- > connect (' 127.0.0.1 subscription, 6379); $strChannel = 'Test_bihu_channel';// subscription echo'-subscribe to the channel {$strChannel} 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 yuan, 6379); $strKey =' Test_bihu_comments';// setting initial value $redis- > set ($strKey, 0); $redis- > INCR ($strKey); / / + 1$ strNowCount = $redis- > get ($strKey); echo "- current quantity is {$strNowCount}.--"
The ranking list is practical.
$redis- > connect ('127.0.0.1 storage, 6379); $strKey =' Test_bihu_score';// storage data $redis- > zadd ($strKey,'50 stores, json_encode (['name' = >' Tom'])); $redis- > zadd ($strKey,'70 percent, json_encode (['name' = >' John'])); $redis- > zadd ($strKey,'90 stores, json_encode (['name' = >' Jerry'])) $redis- > zadd ($strKey,'30 percent, json_encode (['name' = >' Job'])); $redis- > zadd ($strKey, '100 percent, json_encode ([' name' = > 'LiMing'])); $dataOne = $redis- > ZREVRANGE ($strKey, 0,-1, true); echo "- {$strKey} sort from largest to smallest; print_r ($dataOne); $dataTwo = $redis- > ZRANGE ($strKey, 0,-1, true) Echo "- {$strKey} sort from small to large; 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';// acquisition 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 exec / if the monitored key has changed since the call to watch, the whole transaction will fail so far, and the study of "what are the common usage scenarios of Redis" is over. I hope you can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.