1 header("Content-Type:text/html;charset=utf-8"); 2 /* 3 PHP设置分布式memcache存取 4 5 */ 6 //创建memcache对象 7 $mem = new Memcache; 8 9 //连接memcache服务器 10 $mem -> connect('localhost',11211); 11 $mem -> addServer('192.168.1.102',11211); //向服务器中添加一台服务器 12 13 14 /*$mem -> add('one','this is memcache test',MEMCACHE_COMPRESSED,1000); 15 $mem -> add('two',array('111','222','333'),MEMCACHE_COMPRESSED,0); 16 $mem -> add('three',new Test(),MEMCACHE_COMPRESSED,0); 17 $mem -> add('four',100,MEMCACHE_COMPRESSED,0);*/ 18 19 //数据库的连接和操作 20 21 $key = "mydata"; 22 //直接从内存memcache要数据 23 $data = $mem -> get($key); 24 //如果用数据就从内容中返回,如果没有才连接数据库,执行SQL语句 25 26 if(empty($data)){ 27 28 $sql = "select `id`,`title`,`author`,`content`,`add_time` from `news` order by `id`=1"; 29 30 try{ 31 $pdo = new PDO("mysql:host=localhost;dbname=ci",'root','root'); 32 //var_dump($pdo); 33 }catch(PDOException $e){ 34 echo "数据库链接失败!".$e->getMessage($sql); 35 } 36 37 //获取数据,执行查询语句 38 $stmt = $pdo -> prepare($sql); 39 40 $stmt -> execute(); 41 42 $data = $stmt -> fetchAll(PDO::FETCH_ASSOC); 43 44 $mem -> add($key,$data,MEMCACHE_COMPRESSED,10); 45 46 echo "这是第一次访问,从数据库获取的数据并放到了内存中!"; 47 } 48 echo "<pre>"; 49 print_r($data); 50 echo "</pre>"; 51 //关闭memcache连接 52 $mem -> close();