在项目中,涉及大访问量时,合理的使用缓存能减轻数据库的压力,同时提升用户体验。即在非实时性的需求的前提下,一小段时间内(若干秒),用于显示的数据从缓存中获取的,而不用直接读取数据库,能有效的减少数据库的读取压力。这里记录一下php语言使用memcache的情形:

      首先,我们建立一个memcachepool,可以根据不同的配置读取,生成不同的memcache实例。用到$memcache->addServer($host,$port,$flag);向连接池中添加一个memcache服务器。代码示例如下

 1 class memcachePool{
 2      private static $instance;
 3      private $memcacheList = array();
 4     private function __construct(){
 5 
 6     }
 7      public static function getInstance(){
 8          if(self::$instance != null)
 9              return self::$instance;
10          self::$instance = new memcachePool();
11          return self::$instance;
12      }
13     /**
14      * get memcache object from pool
15      * @param  [type] $host 服务器
16      * @param  [type] $port 端口
17      * @param  [type] $flag 控制是否使用持久化连接。默认TRUE
18      * @return [type]
19      */
20      public function getMemcache($host,$port,$flag){
21          if(isset($this->memcacheList[$host.$port]))
22              return $this->memcacheList[$host.$port];
23 
24         $memcache = new Memcache();
25         // 向连接池中添加一个memcache服务器
26         $memcache->addServer($host,$port,$flag);
27         //开启大值自动压缩,第一个参数表示处理数据大小的临界点,第二个参数表示压缩的比例,默认为0.2
28         $memcache->setCompressThreshold(2000,0.2);
29         $this->memcacheList[$host.$port] = $memcache;
30         return $memcache;
31      }
32  }
View Code

相关文章:

  • 2021-05-31
  • 2021-11-15
  • 2022-12-23
  • 2022-02-16
  • 2021-07-19
  • 2022-12-23
  • 2022-03-08
  • 2022-01-21
猜你喜欢
  • 2022-12-23
  • 2021-09-16
  • 2022-12-23
  • 2021-05-06
  • 2021-08-04
相关资源
相似解决方案