PHP-implemented Redis multi-database selection function Singleton class, phpredis
This example describes the single-instance type of the Redis multi-database selection function implemented by PHP. We will share this with you for your reference. The details are as follows:
Preface
Some people in the QQ Group asked redis how to select multiple databases and implemented them using php. I hope you can give me more advice.
Code
<? Phpclass MultiRedisConnect {/*** hostname ** @ var string */const REDISHOSTNAME = "127.0.0.1";/*** port ** @ var int */const REDISPORT = 6379; /*** timeout *** @ var int */const REDISTIMEOUT = 0;/*** password *** @ var string */const REDISPASSWORD = "123456 "; /*** class Singleton array ** @ var array */private static $ instance = array (); /*** redis connection handle ** @ var object */private $ redis;/*** hash key * * @ Var int */private $ hash;/*** private constructor to prevent out-of-class instantiation ** @ param int $ dbnumber */private function _ construct ($ dbnumber) {$ dbnumber = (int) $ dbnumber; $ this-> hash = $ dbnumber; $ this-> redis = new Redis (); $ this-> redis-> connect (self: REDISHOSTNAME, self: REDISPORT, self: REDISTIMEOUT); $ this-> redis-> auth (self: REDISPASSWORD ); $ this-> redis-> select ($ dbnumber);} private function _ clone () {}/*** get Class Singleton ** @ param int $ dbnumber * @ return object */public static function getRedisInstance ($ dbnumber) {$ hash = (int) $ dbnumber; if (! Isset (self ::$ instance [$ hash]) {self ::$ instance [$ hash] = new MultiRedisConnect ($ dbnumber);} return self :: $ instance [$ hash];}/*** get the connection instance of redis ** @ return object */public function getRedisConnect () {return $ this-> redis ;} /*** clear a singleton when it is disabled */public function _ destruct () {$ key = $ this-> hash; self :: $ instances [$ key]-> redis-> close (); self ::$ instances [$ key] = null ;}}?>