这段时间作一个商城集合项目,通过第三方的接口获取京东的数据,展示给用户,下单,支付之类全部通过接口完成,本地只有购物车和订单表

上线后碰到个问题,第三方的接口,获取数据,时快时慢,慢的时候实在是让客户无法忍受

所以给了个方案是把接口数据缓存到服务器,然后提升访问速度,提高用户体验,AI了一个简单的缓存方法,现实中使用起来效果很nice,现在把代码和改造原代码的使用方法分享出来

//缓存方法
    function cached_api_call(string $cacheKey, callable $callback, int $expire = 3600)
    {
        // 从缓存获取数据
        $cache = thinkfacadeCache::instance();
        $data = $cache->get($cacheKey);
        // dump($data);

        // 缓存命中,直接返回
        if ($data !== false && $data !== null) {
            return $data;
        }

        // 缓存未命中,执行实际接口调用
        $data = $callback();
// dump($data);
        // 存入缓存
        $cache->set($cacheKey, $data, $expire);

        return $data;
    }

    public function clearCache($cacheKey)
    {
        // $cacheKey = 'third_party:user_info:' . $userId;
        thinkfacadeCache::delete($cacheKey);
        return true;
    }

    //获取所有分类
    public function getCategory(Request $request)
    {
        $groupName = $request->post('groupName', '');
        $groupLevel = $request->post('groupLevel', '');
        // $tree = (new ShopjdBasic)->getCategory($groupName, $groupLevel);
        // $tree = (new ShopjdBasic)->getCategory('', 1)['data'];
        //  $tree2 = (new ShopjdBasic)->getCategory('', 2)['data'];
        //  foreach ($tree as $k => $v) {
        //      $tree[$k]['children'] = [];
        //      foreach ($tree2 as $v2) {
        //          if ($v2['parentId'] == $v['id']) {
        //              $tree[$k]['children'][] = $v2;
        //          }
        //      }
        //  }

        //  //轮播图
        //  $banner = Db::name('shopjd_brand')->where(['id' => 1])->value('bgUrl');
        //  $banner = $banner ? explode(',', $banner) : [];

        //  return json(['code' => 200, 'msg' => 'success', 'data' => compact(
        //      'tree',
        //      'banner'
        //  )]);

        // $this->clearCache('shopjd_category_' . $groupName . '_' . $groupLevel);

        $cache = $this->cached_api_call('shopjd_category_' . $groupName . '_' . $groupLevel,  function () use ($groupName, $groupLevel) {
            $tree = (new ShopjdBasic)->getCategory('', 1)['data'];
            $tree2 = (new ShopjdBasic)->getCategory('', 2)['data'];
            foreach ($tree as $k => $v) {
                $tree[$k]['children'] = [];
                foreach ($tree2 as $v2) {
                    if ($v2['parentId'] == $v['id']) {
                        $tree[$k]['children'][] = $v2;
                    }
                }
            }

            //轮播图
            $banner = Db::name('shopjd_brand')->where(['id' => 1])->value('bgUrl');
            $banner = $banner ? explode(',', $banner) : [];

            return ['code' => 200, 'msg' => 'success', 'data' => compact(
                'tree',
                'banner'
            )];
        });
        return json($cache);
    }


点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
0.127605s