WeightConfigController.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Redis;
  6. class WeightConfigController extends Controller
  7. {
  8. const REDIS_KEY_CONFIG = 'WeightConfig1234:config';
  9. const REDIS_KEY_CLICKS = 'WeightConfig1234:clicks';
  10. const REDIS_KEY_CLICKS_DAILY_PREFIX = 'WeightConfig1234:clicks:daily:';
  11. const REDIS_KEY_SHOW = 'WeightConfig1234:show';
  12. const REDIS_KEY_SHOW_DAILY_PREFIX = 'WeightConfig1234:show:daily:';
  13. /** 每日明细 Redis 过期时间(仅保留约 3 天) */
  14. const DAILY_STATS_TTL_SECONDS = 86400 * 3;
  15. const VALID_IDS = [1, 2, 3, 4];
  16. public static function defaultConfig()
  17. {
  18. return [1 => 20, 2 => 30, 3 => 40, 4 => 10];
  19. }
  20. public static function getConfig()
  21. {
  22. $raw = Redis::get(self::REDIS_KEY_CONFIG);
  23. if (!$raw) {
  24. return self::defaultConfig();
  25. }
  26. $data = json_decode($raw, true);
  27. if (!is_array($data)) {
  28. return self::defaultConfig();
  29. }
  30. $result = [];
  31. foreach (self::VALID_IDS as $id) {
  32. $result[$id] = isset($data[$id]) ? intval($data[$id]) : 0;
  33. }
  34. return $result;
  35. }
  36. /**
  37. * 传 id;若请求中带参数 show(任意非 null 值,含空字符串或 0),只累计曝光统计 WeightConfig1234:show,不累计点击。
  38. */
  39. public function clickRecord(Request $request)
  40. {
  41. $id = intval($request->input('id'));
  42. if (!in_array($id, self::VALID_IDS)) {
  43. return apiReturnFail('invalid id');
  44. }
  45. if ($request->exists('type')) {
  46. Redis::hincrby(self::REDIS_KEY_SHOW, $id, 1);
  47. $dailyShowKey = self::REDIS_KEY_SHOW_DAILY_PREFIX . date('Y-m-d');
  48. Redis::hincrby($dailyShowKey, $id, 1);
  49. Redis::expire($dailyShowKey, self::DAILY_STATS_TTL_SECONDS);
  50. return apiReturnSuc(['id' => $id, 'type' => 'show']);
  51. }
  52. Redis::hincrby(self::REDIS_KEY_CLICKS, $id, 1);
  53. $dailyKey = self::REDIS_KEY_CLICKS_DAILY_PREFIX . date('Y-m-d');
  54. Redis::hincrby($dailyKey, $id, 1);
  55. Redis::expire($dailyKey, self::DAILY_STATS_TTL_SECONDS);
  56. return apiReturnSuc(['id' => $id, 'type' => 'click']);
  57. }
  58. }