Home>
<?php
/**
 * redis operation, support master/slave load cluster
 *
 * @author jackluo
 * /
class rediscluster {
  //Whether to use m/s read-write cluster solution
  private $_isusecluster=false;
  //slave handle tag
  private $_sn=0;
  //server connection handle
  private $_linkhandle=array (
    "master" =>null, //only supports one master
    "slave" =>array (), //can have multiple slaves
  );
  /**
   * Constructor
   *
   * @param boolean $isusecluster whether to use m/s scheme
   * /
  public function __construct ($isusecluster=false) {
    $this->_isusecluster=$isusecluster;
  }
  /**
   * connect to the server,Note:long connections are used here,Improve efficiency,But will not close automatically
   *
   * @param array $config redis server configuration
   * @param boolean $ismaster Whether the currently added server is the master server
   * @return boolean
   * /
  public function connect ($config=array ("host" =>"127.0.0.1", "port" =>6379), $ismaster=true) {
    //default port
    if (! isset ($config ["port"])) {
      $config ["port"]=6379;
    }
    //set master connection
    if ($ismaster) {
      $this->_linkhandle ["master"]=new redis ();
      $ret=$this->_linkhandle ["master"]->pconnect ($config ["host"], $config ["port"]);
    } else {
      //multiple slave connections
      $this->_linkhandle ["slave"] [$this->_sn]=new redis ();
      $ret=$this->_linkhandle ["slave"] [$this->
      ++ $this->_sn;
    }
    return $ret;
  }
  /**
   * Close the connection
   *
   * @param int $flag close selection 0:close master 1:close slave 2:close all
   * @return boolean
   * /
  public function close ($flag=2) {
    switch ($flag) {
      //close master
      case 0:
        $this->getredis ()->close ();
      break;
      //close slave
      case 1:
        for ($i=0;$i<$this->_ sn;++ $i) {
          $this->_linkhandle ["slave"] [$i]->close ();
        }
      break;
      //close all
      case 1:
        $this->getredis ()->close ();
        for ($i=0;$i<$this->_sn;++ $i) {
          $this->_linkhandle ["slave"] [$i]->close ();
        }
      break;
    }
    return true;
  }
  /**
   * There are more operations to get the original redis object
   *
   * @param boolean $ismaster returns the type of server true:returns master false:returns slave
   * @param boolean $slaveone Returns the slave selection true:load balancing returns a slave selection randomly False:returns all slave selections
   * @return redis object
   * /
  public function getredis ($ismaster=true, $slaveone=true) {
    //only return master
    if ($ismaster) {
      return $this->_linkhandle ["master"];
    } else {
      return $slaveone?$this->_ getslaveredis ():$this->_ linkhandle ["slave"];
    }
  }
  /**
   * Write cache
   *
   * @param string $key group key
   * @param string $value cache value
   * @param int $expire expiration time, 0:No expiration time
   * /
  public function set ($key, $value, $expire=0) {
    //never time out
    if ($expire == 0) {
      $ret=$this->getredis ()->set ($key, $value);
    } else {
      $ret=$this->getredis ()->setex ($key, $expire, $value);
    }
    return $ret;
  }
  /**
   * Read cache
   *
   * @param string $key cache key, support multiple fetches at once $key=array ("key1", "key2")
   * @return string || boolean returns false on failure, returns string on success
   * /
  public function get ($key) {
    //whether to take multiple values ​​at once
    $func=is_array ($key)?"mget":"get";
    //not using m/s
    if (! $this->_isusecluster) {
      return $this->getredis ()->{$func} ($key);
    }
    //used m/s
    return $this->_getslaveredis ()->{$func} ($key);
  }
/*
  //magic function
  public function __call ($name, $arguments) {
    return call_user_func ($name, $arguments);
  }
* /
  /**
   * Conditional setting cache,Set if key is not stored,Setting failed when it exists
   *
   * @param string $key cache key
   * @param string $value cache value
   * @return boolean
   * /
  public function setnx ($key, $value) {
    return $this->getredis ()->setnx ($key, $value);
  }
  /**
   * Delete cache
   *
   * @param string || array $key cache key, supports a single key:"key1" or multiple keys:array ("key1", "key2")
   * @return int number of keys deleted
   * /
  public function remove ($key) {
    //$key =>"key1" || array ("key1", "key2")
    return $this->getredis ()->delete ($key);
  }
  /**
   * Value addition operation,Similar to ++ $i, if the key does not exist, it is automatically set to 0 and the addition operation is performed.
   *
   * @param string $key cache key
   * @param int $default The default value during operation
   * @return int value after operation
   * /
  public function incr ($key, $default=1) {
    if ($default == 1) {
      return $this->getredis ()->incr ($key);
    } else {
      return $this->getredis ()->incrby ($key, $default);
    }
  }
  /**
   * Value reduction operation,Similar to-$i, if the key does not exist, it is automatically set to 0 and then the subtraction operation is performed.
   *
   * @param string $key cache key
   * @param int $default The default value during operation
   * @return int value after operation
   * /
  public function decr ($key, $default=1) {
    if ($default == 1) {
      return $this->getredis ()->decr ($key);
    } else {
      return $this->getredis ()->decrby ($key, $default);
    }
  }
  /**
   * Empty the current database
   *
   * @return boolean
   * /
  public function clear () {
    return $this->getredis ()->flushdb ();
  }
  /* ===================== The following private methods ===================== /
  /**
   * Random hash to get redis slave server handle
   *
   * @return redis object
   * /
  private function _getslaveredis () {
    //return directly to a slave
    if ($this->_sn<= 1) {
      return $this->_linkhandle ["slave"] [0];
    }
    //Random hash to get the handle of the slave
    $hash=$this->_hashid (mt_rand (), $this->_sn);
    return $this->_linkhandle ["slave"] [$hash];
  }
  /**
   * Get the value between 0 and m-1 after hash according to the id
   *
   * @param string $id
   * @param int $m
   * @return int
   * /
  private function _hashid ($id, $m=10)
  {
    //Convert string k to a value between 0 and m-1 as the hash address of the corresponding record
    $k=md5 ($id);
    $l=strlen ($k);
    $b=bin2hex ($k);
    $h=0;
    for ($i=0;$i<$l;$i ++)
    {
      //addition mode hash
      $h +=substr ($b, $i * 2,2);
    }
    $hash=($h * 1)%$m;
    return $hash;
  }
  /**
   * lpush
   * /
  public function lpush ($key, $value) {
    return $this->getredis ()->lpush ($key, $value);
  }
  /**
   * add lpop
   * /
  public function lpop ($key) {
    return $this->getredis ()->lpop ($key);
  }
  /**
   * lrange
   * /
  public function lrange ($key, $start, $end) {
    return $this->getredis ()->lrange ($key, $start, $end);
  }
  /**
   * set hash opeation
   * /
  public function hset ($name, $key, $value) {
    if (is_array ($value)) {
      return $this->getredis ()->hset ($name, $key, serialize ($value));
    }
    return $this->getredis ()->hset ($name, $key, $value);
  }
  /**
   * get hash opeation
   * /
  public function hget ($name, $key=null, $serialize=true) {
    if ($key) {
      $row=$this->getredis ()->hget ($name, $key);
      if ($row && $serialize) {
        unserialize ($row);
      }
      return $row;
    }
    return $this->getredis ()->hgetall ($name);
  }
  /**
   * delete hash opeation
   * /
  public function hdel ($name, $key=null) {
    if ($key) {
      return $this->getredis ()->hdel ($name, $key);
    }
    return $this->getredis ()->hdel ($name);
  }
  /**
   * transaction start
   * /
  public function multi () {
    return $this->getredis ()->multi ();
  }
  /**
   * transaction send
   * /
  public function exec () {
    return $this->getredis ()->exec ();
  }
} //end class
//================== test demo ==================
//only one redis application
$redis=new rediscluster ();
$redis->connect (array ("host" =>"127.0.0.1", "port" =>6379));
//*
$cron_id=10001;
$cron_key="cron_list";//
$phone_key="phone_list:". $cron_id;//
//cron info
$cron=$redis->hget ($cron_key, $cron_id);
if (empty ($cron)) {
  $cron=array ("id" =>10, "name" =>"jackluo");//mysql data
  $redis->hset ($cron_key, $cron_id, $cron);//set redis
}
//phone list
$phone_list=$redis->lrange ($phone_key, 0, -1);
print_r ($phone_list);
if (empty ($phone_list)) {
  $phone_list=explode (",", "13228191831,18608041585");//mysql data
  //join list
  if ($phone_list) {
    $redis->multi ();
    foreach ($phone_list as $phone) {
      $redis->lpush ($phone_key, $phone);
    }
    $redis->exec ();
  }
}
print_r ($phone_list);
/* $list=$redis->hget ($cron_list,);
var_dump ($list);* /
//* /
//$redis->set ("id", 35);
/*
  $redis->lpush ("test", "1111");
  $redis->lpush ("test", "2222");
  $redis->lpush ("test", "3333");
  $list=$redis->lrange ("test", 0, -1);
  print_r ($list);
  $lpop=$redis->lpop ("test");
  print_r ($lpop);
  $lpop=$redis->lpop ("test");
  print_r ($lpop);
  $lpop=$redis->lpop ("test");
  print_r ($lpop);
* /
//var_dump ($redis->get ("id"));
php
  • Previous delete and delete operators in javascript
  • Next php classic algorithm highlights