memcache案例

<?php
		header("content-type:text/html;charset=utf-8");<pre name="code" class="python">	public function lists(){
		$search=$_GET['search'];//搜索的值
		$mem=new Memcache;//连接memcache
		$mem->connect("127.0.0.1",11211);
		$pd=$mem->get("$search");//获得到搜索到的值
		if($pd){
			if($pd<=9){
				$pd++;
				$mem->replace("$search",$pd,0,600);
				$arr=$this->db->like("content",$search)->get("zk1")->result_array();
				echo json_encode($arr);
			}else if($pd==10){
				$arr=$this->db->like("content",$search)->get("zk1")->result_array();
				$mem->replace("$search",$arr,0,600);
				echo json_encode($arr);
			}else{
				echo json_encode($pd);
			}
		}else{
				$mem->set("$search",0,0,600);
				$arr=$this->db->like("content",$search)->get("zk1")->result_array();
				echo json_encode($arr);
		}
	}


2.搜索数据,前十次从数据库中搜索数据,后十次从memcache中搜索数据

	public function lists(){
		$search=$_GET['search'];//搜索的值
		$mem=new Memcache;//连接memcache
		$mem->connect("127.0.0.1",11211);
		$pd=$mem->get("$search");//获得到搜索到的值
		if($pd){
			if($pd<=9){
				$pd++;
				$mem->replace("$search",$pd,0,600);
				$arr=$this->db->like("content",$search)->get("zk1")->result_array();
				echo json_encode($arr);
			}else if($pd==10){
				$arr=$this->db->like("content",$search)->get("zk1")->result_array();
				$mem->replace("$search",$arr,0,600);
				echo json_encode($arr);
			}else{
				echo json_encode($pd);
			}
		}else{
				$mem->set("$search",0,0,600);
				$arr=$this->db->like("content",$search)->get("zk1")->result_array();
				echo json_encode($arr);
		}
	}



3.获取数据

<script>
	$(function(){
		$(document).on("click",".search1",function(){
			var search=$("#search").val();
			$.getJSON("<?php echo site_url('welcome/lists') ?>",{search:search},function(obj){
				var html = '<table border="1">';
					html+='<th>编号</th><th>用户名</th>';
					for(var i = 0;i<obj.length;i++){
						html+='<tr>';
						html+='<td>'+obj[i]['id']+'</td>';
						html+='<td>'+obj[i]['content']+'</td>';
						html+='<tr>';
					}
					html+='</table>';
					$("#list").html(html);

			})
		})		
	})
</script>



你可能感兴趣的:(memcache案例)