php-redis message subscription notes

Recently I learned about the knowledge of php-redis relevant, which has a feature called publish-subscribe, Redis publish-subscribe (pub / sub) is a messaging mode of communication, the sender (pub) to send a message, subscribers (sub) receive messages.

Php code directly on the following:

Normal - [] sender pub - pub.php

. 1  $ Redis = new new the Redis ();
 2  $ Redis -> Connect ( '127.0.0.1', 6379 );
 . 3  $ Redis -> the auth ( 'requirepass' );
 . 4  
. 5  $ RES = $ Redis -> publish (' Channel ', DATE (' Ymd H: I: S ' ));
 . 6  var_dump ( $ RES ); // return a success, else return 0

Normal - [sub] subscribers - sub.php

1 $redis = new Redis();
2 $redis->connect('127.0.0.1', 6379);
3 $redis->auth('requirepass');
4 $redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
5 
6 function callback ($redisObj, $channel, $msg){
7     echo 'ChannelName is '.$channel.', Msg is '.$msg; //ChannelName is channel, Msg is 2019-07-17 09:53:55
8 }
9 $redis->subscribe(['channel'], 'callback');

This transmission principle can be understood and subscribed to transmit one end, the other end receives the message immediately, precisely, is to send a message through the channel to the channel, the other end of the channel subscription channels can immediately receive the message.

 [Validity] key settings - pub.php

. 1  $ Job . = 'Notify #' DATE ( 'YmdHis' );
 2  $ RES = $ Redis -> SETEX ( $ Job , 10, 'Waiting' );
 . 3  var_dump ( $ RES // Returns bool (true success;) ), failed to return bool (false)

[Subscribe] key space news - sub.php

. 1  $ redisKey = '0 __keyevent @ __: expired The' ; // This format is fixed, a library represents 0, 0 use default Redis first library
 2  $ Redis -> psubscribe ([ $ redisKey ], 'callBack' );
 . 3  function  callBack ( $ redisObj , $ pattern , $ Channel , $ MSG ) {
 . 4      echo  $ MSG . "\ R & lt \ n-" ; // # 20,190,717,100,350 Notify
 . 5 }

This transmission principle and subscriptions can be understood as expired when the key will automatically send a message, open the other end of the subscription key space message can receive news.

Special Note: Because the incident started after the subscription is blocked executed, it is necessary to wait for the terminal has been hung subscription, this situation can only meet the test development, if it is practical to die, this time we want to listen for background always run as the guardian of hope the same process in the background, Linux systems, you can use the nohup command, the specific usage continued.

Guess you like

Origin www.cnblogs.com/firstlady/p/11199091.html