使用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, '異常錯誤');
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章