使用redis实现计数器

计数器获取,参数appId ,返回数量,redis 保存 过期时间14天 log:counter
每调用一次随机增加 1~5

 public function actionFetchCounter()
    {
        try {
            $params = $_GET ?: $_POST;
            if (empty($params['appId'])) {
                $this->jsonReturnError(Constants::CODE_FAILED, '缺少参数appId');
            }
            $key = 'logcenter:counter:' . $params['appId'];
            $rand = mt_rand(1, 5);
            $redis = RedisClient::getInstance();//使用默认的redis
            $redis->expire($key, 14 * 86400);//设置14天的过期时间
            $redis->incrBy($key, $rand);
            $counter = $redis->get($key);

            $this->jsonReturnSuccess(Constants::CODE_SUCCESS, ['counter' => $counter], '成功');
        } catch (\Exception $e) {
            $this->jsonReturnError(Constants::CODE_FAILED, '异常错误');
        }
    }

猜你喜欢

转载自blog.51cto.com/11315052/2452166