<?php namespace App\Service; use App\Service\BaseService; use Illuminate\Support\Facades\Redis; /* * redis操做相關方法 */ class RedisService extends BaseService { /** * * @param string $key reids的get的key * @param string $class 待執行的方法的class App\Service\AdminService * @param string $function 待執行的方法的function getSupplyNum * @param array $parameters 待執行的方法的parameters 參數 ...$parameters [] 數組自動綁定 * @param int $survivalTime redis存儲時間 * $returnData 調用方法是否必須有數據 * @return type * @throws \Exception */ public static function get(string $key, string $class = '', string $function = '', array $parameters = [], int $survivalTime = 3600, $returnData = true) { if (empty($key)) { throw new \Exception('key不能爲空'); } $keyValue = Redis::get($key); if (empty($keyValue)) { if (!method_exists($class, $function)) { throw new \Exception($class . '此類的方法' . $function . '不存在'); } /* * 參數自動綁定,參數位置不能錯 * $value 最好返回是數組, */ $value = $class::$function(...$parameters); // p($value); if (empty($value) && $returnData) { throw new \Exception($class . '此類的方法' . $function . '返回數據爲空,請檢查調用方法'); } Redis::set($key, json_encode($value)); Redis::expire($key, $survivalTime); return json_encode($value); } return $keyValue; } }
demo AdminServicephp
//近一個月數據 public static function getMonthSaleOrderData($shop_id) { //近一個月訂單總金額 $saleOrderKey = 'MonthSaleOrder' . $shop_id; $data = RedisService::get($saleOrderKey, 'App\Service\AdminService', 'MonthSaleOrderData', [$shop_id]); return json_decode($data, true); } public static function MonthSaleOrderData($shop_id) { $time = get_lately_month_start_to_end(); $query = SaleOrder::where('shop_id', $shop_id)->where('is_delete', 10) ->where('create_time', '>=', $time['start_time']) ->where('create_time', '<=', $time['end_time']); $saleOrderAmount = $query->sum('order_amount'); $saleOrderNumber = $query->sum('order_number'); $saleOrderCount = $query->count(); $data = [ 'saleOrderAmount' => $saleOrderAmount, 'saleOrderNumber' => $saleOrderNumber, 'saleOrderCount' => $saleOrderCount, ]; return $data; }