PHP实现的Redis多库选择功能单例类

时间:2022-11-05 18:01:40

本文实例讲述了PHP实现的Redis多库选择功能单例类。分享给大家供大家参考,具体如下:

前言

qq群里有同学问redis如何进行多库选择,用php实现了一下,还望各位多多指点

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
class 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";
  /**
   * 类单例数组
   *
   * @var array
   */
  private static $instance = array();
  /**
   * redis连接句柄
   *
   * @var object
   */
  private $redis;
  /**
   * hash的key
   *
   * @var int
   */
  private $hash;
  /**
   * 私有化构造函数,防止类外实例化
   *
   * @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 ()
  {}
  /**
   * 获取类单例
   *
   * @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];
  }
  /**
   * 获取redis的连接实例
   *
   * @return object
   */
  public function getRedisConnect ()
  {
    return $this->redis;
  }
  /**
   * 关闭单例时做清理工作
   */
  public function __destruct ()
  {
    $key = $this->hash;
    self::$instances[$key]->redis->close();
    self::$instances[$key] = null;
  }
}
?>

希望本文所述对大家PHP程序设计有所帮助。