dongxixiu9134 2016-05-10 18:15
浏览 79
已采纳

缓存API数据Laravel 5.2

I'am working on the Halo 5 API. I applied to get a higher rate limit for the API, and one of the responses I got was this:

Can you please provide us more details about which calls you’re making to the APIs and if you’re using any caching? Specifically we would recommend caching match and event details and metadata as those rarely change.

I get the part when they say "which calls you're making", but the caching part, I have never worked with that. I get the basic parts of caching, that it speeds up your API, but I just wouldn't know how to implement it into my API.

I would want to know how to cache some data in my app. Here is a basic example of how I would get players medals from the API.

Route:

Route::group(['middleware' => ['web']], function () {

    /** Get the Home Page **/
    Route::get('/', 'HomeController@index');


    /** Loads ALL the player stats, (including Medals, for this example) **/
    Route::post('/Player/Stats', [
        'as' => 'player-stats',
        'uses' => 'StatsController@index'
    ]);

});

My GetDataController to call the API Header to get Players Medals:

<?php

namespace App\Http\Controllers\GetData;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;

use GuzzleHttp;
use App\Http\Controllers\Controller;

class GetDataController extends Controller {


    /**
     * Fetch a Players Arena Stats
     *
     * @param $gamertag
     * @return mixed
     */
    public function getPlayerArenaStats($gamertag) {

        $client = new GuzzleHttp\Client();

        $baseURL = 'https://www.haloapi.com/stats/h5/servicerecords/arena?players=' . $gamertag;

        $res = $client->request('GET', $baseURL, [
            'headers' => [
                'Ocp-Apim-Subscription-Key' => env('Ocp-Apim-Subscription-Key')
            ]
        ]);

        if ($res->getStatusCode() == 200) {
            return $result = json_decode($res->getBody());
        } elseif ($res->getStatusCode() == 404) {
            return $result = redirect()->route('/');
        }

        return $res;
    }

}

My MedalController to get the Medals from a Player:

<?php

namespace App\Http\Controllers;

use GuzzleHttp;
use App\Http\Controllers\Controller;

class MedalController extends Controller {



    public function getArenaMedals($playerArenaMedalStats) {

        $results = collect($playerArenaMedalStats->Results[0]->Result->ArenaStats->MedalAwards);

        $array = $results->sortByDesc('Count')->map(function ($item, $key) {
            return [
                'MedalId' => $item->MedalId,
                'Count' => $item->Count,
            ];
        });

        return $array;
    }


}

And this is the function to display the Players medals into view:

 public function index(Request $request) {

        // Validate Gamer-tag
        $this->validate($request, [
            'gamertag' => 'required|max:16|min:1',
        ]);

        // Get the Gamer-tag inserted into search bar
        $gamertag = Input::get('gamertag');




        // Get Players Medal Stats for Arena
        $playerArenaMedalStats = app('App\Http\Controllers\GetData\GetDataController')->getPlayerArenaStats($gamertag);
        $playerArenaMedalStatsArray = app('App\Http\Controllers\MedalController')->getArenaMedals($playerArenaMedalStats);
        $arenaMedals = json_decode($playerArenaMedalStatsArray, true);



         return view('player.stats')
            ->with('arenaMedals', $arenaMedals)

}

Would you guys know how to cache this data?

(FYI, there are about 189 different medals from the JSON call, so its a pretty big API call). I also read the documentation about caching for Laravel, but still need clarification.

  • 写回答

1条回答 默认 最新

  • duanlan6259 2016-05-10 19:06
    关注

    You could use Laravel Cache.

    Try this:

    public function getPlayerArenaStats($gamertag) {
    .... some code ....
        $res = $client->request('GET', $baseURL, [
            'headers' => [
                'Ocp-Apim-Subscription-Key' => env('Ocp-Apim-Subscription-Key')
            ]
        ]);
        Cache::put('medals', $res, 30); //30 minutes
        .... more code...
    }
    
    public function index(Request $request) {
    ...
    if (Cache::has('medals')) {
        $playerArenaMedalStats = Cache::get('medals');
    } else {
        app('App\Http\Controllers\GetData\GetDataController')->getPlayerArenaStats($gamertag);
    }
    ...
    

    Of course, you will need to do better than this, to store only the information you need. Check the docs here: https://laravel.com/docs/5.1/cache

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料