分享你们一个php写的redis计时器

分享你们一个redis计时器,可稍微改下,用于 分,时,日,周,月计数

业务场景实现在多,另外UID不一定都是用户ID,可以是任何的能区分唯一的值东西

例如,手机号,视频ID,system, system_view等字符串

/**
 * 日计数器,每日相关的计数器
 * Created by PhpStorm.
 * User: dongjw321@163.com
 * Date: 2016/11/28
 * Time: 16:57
 */

namespace Api\Libraries\User;

use DongPHP\System\Libraries\Cache;

class Counter
{

    protected $key_prefix;

    protected static $data;


    const SMS_CODE       = 11; //手机验证码
    const TOTAL_DOWNLOAD = 12; //总下载次数
    const FREE_DOWNLOAD  = 14; //免费次数
    const TODAY_TOTAL_DOWNLOAD = 15; // 今日付费下载次数
    const LARGE_APP_FREE_DOWNLOAD = 16; // 大包免费下载次数

    protected function __construct()
    {
        $this->key_prefix = 'counter:';
    }

    public static function add($uid, $type, $param='', $value=1)
    {
        $instance = new static;
        $key      = $instance->getKey($uid, $type, $param);
        $total    = Cache::redis('default')->incrBy($key, $value);
        if ($total == $value) {
            Cache::redis('default')->expireAt($key, strtotime(date("Y-m-d 23:59:59")));//设置key的有效器
        }
        self::$data[$key] = $total;
        return self::$data[$key];
    }

    public static function get($uid, $type, $param='')
    {
        $instance = new static;
        $key = $instance->getKey($uid, $type, $param);
        if (!isset(self::$data[$key])) {
            self::$data[$key] = (int)Cache::redis('default')->get($key);
        }
        return self::$data[$key];
    }

    public static function clear($uid, $type, $param='')
    {
        $instance = new static;
        $key = $instance->getKey($uid, $type, $param);
        if (isset(self::$data[$key])) {
            unset(self::$data[$key]);
        }
        return Cache::redis('default')->del($key);
    }

    protected function getKey($uid, $type, $param='')
    {
        if (!$param) {
            $key = md5(date('Ymd_').'_'.$uid.'_'.$type);
        } elseif (is_array($param)) {
            $key = md5(date('Ymd_').'_'.$uid.'_'.$type.'_'.json_encode($param));
        } else {
            $key = md5(date('Ymd_').'_'.$uid.'_'.$type.'_'.$param);
        }
        return $this->key_prefix.$key;
    }
}
讨论数量: 1

:joy: 这种代码就别发了吧

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!