客户端启动请求服务器一次数据,然后再次刷新再次加载数据,每次都直接查数据库怕机器跑不动,听别人说弄缓存,不知道怎么写。。求赐教。你好。我现在是客户端访问服务器,然后我直接查询mysql给客户端数据,不知道这样应该写缓存的?<?php$page=@$_GET["page"] ? $_GET["page"] : 1;$page=($page-1)*10; $conn=mysql_connect("localhost","root",""); mysql_select_db("getjson"); $sql="select * from user order by id desc limit ".$page.",10";$result=mysql_query($sql);echo "{\"name\":[";$hehe=1;while($row=mysql_fetch_assoc($result)){ //数组接收返回$arr=$row;echo json_encode($arr);//编码if($hehe<10){echo",";}$hehe++;}echo"]}";mysql_close($conn);
PHP数据缓存常用页面缓存 静态缓存php页面缓存主要用到的是ob系列函数,如ob_start(),ob_end_flush(),ob_get_contents()静态缓存是指静态化,直接生成HTML或XML等文本文件,有更新的时候重生成一次,适合于不太变化的页面给你个页面缓存的例子function page_cache($ttl = 0) { $ttl = $ttl ? $ttl : PAGE_TTL;//缓存时间,默认3600s $contents = ob_get_contents();//从缓存中获取内容 $contents = "<!--page_ttl:".(time() + $ttl)."-->n".$contents; //加上自定义头部:过期时间=生成时间+缓存时间 file_put_contents(PAGE_FILE, $contents);//写入缓存文件中 ob_end_flush();//释放缓存 }
//我是以文件存储的形势处理缓存$CACHE = cache_read('cache.php');//从文件读取缓存数据if(!$CACHE) {//如果没有缓存 require_once 'cache.func.php';//请求缓存公共文件 cache_all();//生成缓存的方法,自己写,思路就是把数据从数据库查出来,生成文件,不要告诉我不会。 $CACHE = cache_read('cache.php');//读取缓存}}
不知道你的php程度。这是 zend framework的写法Zend_Loader::loadClass('Zend_Cache');$frontendOptions = array('lifetime' => 60 * 5, // 5 minutes'automatic_serialization' => true,);$backendOptions = array('cache_dir' => BASE_PATH . '/application/cache/','file_name_prefix' => 'zend_cache_query','hashed_directory_level' => 2,);$query_cache = Zend_Cache::factory('Core', 'File', $frontendOptions,$backendOptions);$cacheName = 'product_id_' . $id;if(!($result = $query_cache->load($cacheName))) {Zend_Loader::loadClass('Product');$productTable = new Product();$result = $productTable->fetchRow(array('id = ?' => $id));