PHP-implemented Redis multi-database selection function Singleton class, phpredis

Source: Internet
Author: User

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 ;}}?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.