<?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 AdminService
//近一个月数据 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; }