| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141 |
- <?php
- namespace Heanup\Frame\Package\Counter;
- /**
- * 计数器类
- * redis连不上server会抛出异常!!
- */
- class Single extends \Heanup\Frame\Package\Counter
- {
- const CONFIG_CLASS = 'Redis\\Counter';
- const PREFIX = '';
- const EXPIRE = 2592000; // 30 天
- /**
- * 单个读取
- * @param $id
- * @return array
- */
- public static function get($id)
- {
- $key = self::getKey($id);
- try {
- $result = self::getConnection()->get($key);
- $result = intval($result);
- } catch (\Exception $ex) {
- $result = null;
- }
- return $result;
- }
- /**
- * 批量获取
- * @param array $idList
- * @return array|null
- */
- public static function mGet(Array $idList)
- {
- $keyList = array();
- foreach ($idList as $id) {
- $k = self::getKey($id);
- $keyList[$k] = $id;
- }
- try {
- $result = array();
- $data = self::getConnection()->mget(array_keys($keyList));
- $i = 0;
- foreach ($keyList as $k => $v) {
- $result[$v] = intval($data[$i]);
- $i++;
- }
- } catch (\Exception $ex) {
- $result = null;
- }
- return $result;
- }
- /**
- * @param $id
- * @param int $value
- * @return bool
- */
- public static function set($id, $value)
- {
- $key = self::getKey($id);
- try {
- $result = self::getConnection(true)->set($key, $value);
- } catch (\Exception $ex) {
- $result = false;
- }
- return $result;
- }
- /**
- * 加1
- * @param $id
- * @param int $value
- * @return int
- */
- public static function increase($id, $value = 1)
- {
- $key = self::getKey($id);
- $value = abs($value);
- try {
- $result = self::getConnection(true)->incr($key, $value);
- } catch (\Exception $ex) {
- $result = false;
- }
- return $result;
- }
- /**
- * @param $id , 如果值小于0则设为0
- * @param int $value
- * @return int
- */
- public static function decrease($id, $value = 1)
- {
- $key = self::getKey($id);
- $value = abs($value);
- try {
- $result = self::getConnection(true)->decr($key, $value);
- if ($result < 0) {
- $result = self::getConnection(true)->set($key, 0);
- }
- } catch (\Exception $ex) {
- $result = false;
- }
- return $result;
- }
- /**
- * 删除
- * @param $id
- * @return bool
- */
- public static function delete($id)
- {
- $key = self::getKey($id);
- try {
- $result = self::getConnection(true)->delete($key);
- } catch (\Exception $ex) {
- $result = false;
- }
- return $result;
- }
- /**
- * 获取连接池
- * @param bool $isMaster
- * @return \Redis
- */
- protected static function getConnection($isMaster = false)
- {
- $class = get_called_class();
- $configClass = $class::CONFIG_CLASS;
- $redis = new \Heanup\Frame\Library\Redis($configClass);
- $connection = $redis->getConnection($isMaster);
- return $connection;
- }
- }
|