| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- namespace App\Http\Controllers\Api;
- use App\Http\Controllers\Controller;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Redis;
- class WeightConfigController extends Controller
- {
- const REDIS_KEY_CONFIG = 'WeightConfig1234:config';
- const REDIS_KEY_CLICKS = 'WeightConfig1234:clicks';
- const REDIS_KEY_CLICKS_DAILY_PREFIX = 'WeightConfig1234:clicks:daily:';
- const REDIS_KEY_SHOW = 'WeightConfig1234:show';
- const REDIS_KEY_SHOW_DAILY_PREFIX = 'WeightConfig1234:show:daily:';
- /** 每日明细 Redis 过期时间(仅保留约 3 天) */
- const DAILY_STATS_TTL_SECONDS = 86400 * 3;
- const VALID_IDS = [1, 2, 3, 4];
- public static function defaultConfig()
- {
- return [1 => 20, 2 => 30, 3 => 40, 4 => 10];
- }
- public static function getConfig()
- {
- $raw = Redis::get(self::REDIS_KEY_CONFIG);
- if (!$raw) {
- return self::defaultConfig();
- }
- $data = json_decode($raw, true);
- if (!is_array($data)) {
- return self::defaultConfig();
- }
- $result = [];
- foreach (self::VALID_IDS as $id) {
- $result[$id] = isset($data[$id]) ? intval($data[$id]) : 0;
- }
- return $result;
- }
- /**
- * 传 id;若请求中带参数 show(任意非 null 值,含空字符串或 0),只累计曝光统计 WeightConfig1234:show,不累计点击。
- */
- public function clickRecord(Request $request)
- {
- $id = intval($request->input('id'));
- if (!in_array($id, self::VALID_IDS)) {
- return apiReturnFail('invalid id');
- }
- if ($request->exists('type')) {
- Redis::hincrby(self::REDIS_KEY_SHOW, $id, 1);
- $dailyShowKey = self::REDIS_KEY_SHOW_DAILY_PREFIX . date('Y-m-d');
- Redis::hincrby($dailyShowKey, $id, 1);
- Redis::expire($dailyShowKey, self::DAILY_STATS_TTL_SECONDS);
- return apiReturnSuc(['id' => $id, 'type' => 'show']);
- }
- Redis::hincrby(self::REDIS_KEY_CLICKS, $id, 1);
- $dailyKey = self::REDIS_KEY_CLICKS_DAILY_PREFIX . date('Y-m-d');
- Redis::hincrby($dailyKey, $id, 1);
- Redis::expire($dailyKey, self::DAILY_STATS_TTL_SECONDS);
- return apiReturnSuc(['id' => $id, 'type' => 'click']);
- }
- }
|