thinkphp处理海量数据分表机制详细代码
应用thinkphp内置的分表算法处理百万级用户数据.数据表:house_member_0house_member_1house_member_2house_member_3模型中class membermodel extends advmodel {protected $partition = array('field'=>'username','type'=>'id','num'=>'4');public function getdao($data=array()) {$data = empty($data) ? $_post : $data;$table = $this->getpartitiontablename($data);return $this->table($table);}}方法中class memberaction extends baseaction {public function login() {if($this->ispost()) {$this->validtoken();$dao = d('member')->getdao();$res = $dao->where('username = '.$_post['username'])->find();// output 为自定义方法// $isajax - bool$this->output(false);}$this->display();}}/**+----------------------* 得到分表的的数据表名+----------------------* @access public+----------------------* @param array $data 操作的数据+----------------------* @return string+----------------------*/public function getpartitiontablename($data=array()) {// 对数据表进行分区if(isset($data[$this->partition['field']])) {$field = $data[$this->partition['field']];switch($this->partition['type']) {case 'id':// 按照id范围分表$step = $this->partition['expr'];$seq = floor($field / $step)+1;break;case 'year':// 按照年份分表if(!is_numeric($field)) {$field = strtotime($field);}$seq = date('y',$field)-$this->partition['expr']+1;break;case 'mod':// 按照id的模数分表$seq = ($field % $this->partition['num'])+1;break;case 'md5':// 按照md5的序列分表$seq = (ord(substr(md5($field),0,1)) % $this->partition['num'])+1;break;default :if(function_exists($this->partition['type'])) {// 支持指定函数哈希$fun = $this->partition['type'];$seq = (ord(substr($fun($field),0,1)) % $this->partition['num'])+1;}else{// 按照字段的首字母的值分表$seq = (ord($field{0}) % $this->partition['num'])+1;}}return $this->gettablename().'_'.$seq;}else{// 当设置的分表字段不在查询条件或者数据中// 进行联合查询,必须设定 partition['num']$tablename = array();for($i=0;$ipartition['num'];$i++)$tablename[] = 'select * from '.$this->gettablename().'_'.$i;$tablename = '( '.implode( union ,$tablename).') as '.$this->name;return $tablename;}}
?
