缓存 API 数据 Laravel 5.2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37146053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:45:52  来源:igfitidea点击:

Caching API Data Laravel 5.2

phpjsonlaravelcaching

提问by David

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:

我正在研究 Halo 5 API。我申请为 API 获得更高的速率限制,我得到的答复之一是:

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.

您能否向我们提供有关您对 API 进行哪些调用以及是否使用任何缓存的更多详细信息?具体而言,我们建议缓存匹配项和事件详细信息以及元数据,因为它们很少更改。

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.

当他们说“您正在拨打哪个电话”时,我得到了部分,但缓存部分,我从未使用过。我了解缓存的基本部分,它可以加速您的 API,但我只是不知道如何将它实现到我的 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.

我想知道如何在我的应用程序中缓存一些数据。这是我如何从 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:

我的 GetDataController 调用 API Header 来获取玩家奖牌:

<?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:

我的 MedalController 从玩家那里获取奖牌:

<?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.

(仅供参考,JSON 调用有大约 189 个不同的奖牌,因此它是一个非常大的 API 调用)。我还阅读了有关 Laravel 缓存的文档,但仍需要澄清。

回答by Felippe Duarte

You could use Laravel Cache.

你可以使用 Laravel 缓存。

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

当然,您需要做得比这更好,只存储您需要的信息。在此处查看文档:https: //laravel.com/docs/5.1/cache