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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?