momentohq/laravel-example

展示Momento缓存驱动器的Laravel天气应用程序。

v0.3.2 2024-03-27 17:21 UTC

README

logo

Momento Laravel 示例

在这个仓库中,您将看到如何将Momento缓存集成到您的Laravel应用程序中,而不是使用Redis或Memcached。有什么好处?您可能会问。您不必担心Redis/Memcached节点!好奇吗?继续阅读!

通过Docker运行应用程序

在构建Docker镜像之前,在docker目录中创建.env文件,并包含以下环境变量

  • MOMENTO_API_KEY=<您的API密钥>
  • MOMENTO_CACHE_NAME=<您的缓存名称>
  • WEATHER_API_KEY 这是用于天气API的。查看OpenWeather获取API密钥。

如果您没有Momento API密钥,您可以使用Momento控制台生成一个。

为应用程序构建Docker镜像

cd docker
docker build --tag laravel-example .

注意:构建laravel-example镜像涉及到编译PHP gRPC扩展,这可能需要几分钟才能完成。

如果您遇到GitHub API限制,请将GitHub个人访问令牌添加到您的Composer配置中

export COMPOSER_AUTH=<YOUR_GITHUB_ACCESS_TOKEN>
docker build --tag laravel-example --build-arg COMPOSER_AUTH=$COMPOSER_AUTH .

使用此镜像运行Docker容器

docker run -d --env-file .env -p 8000:8000 laravel-example

手动PHP配置

您需要安装以下内容

将仓库和依赖项添加到项目的composer.json

{
  "require": {
    "momentohq/laravel-example": "0.2.3"
  }
}

将Momento配置添加到config/cache.php中的'stores'部分,根据需要调整cache_namedefault_ttl参数

'stores' => [
        ...
        'momento' => [
            'driver' => 'momento',
            'cache_name' => 'my-momento-cache',
            'default_ttl' => 60,
        ],
],

更新.env文件中的缓存驱动条目

CACHE_DRIVER=momento

并在.env文件中添加以下环境变量

  • WEATHER_API_KEY 这是用于天气API的。查看OpenWeather获取API密钥。
  • MOMENTO_API_KEY

如果您没有Momento API密钥,您可以使用Momento控制台生成一个。

运行composer update安装必要的先决条件。

要运行此应用程序

php artisan serve

cURL命令

curl http://127.0.0.1:8000/api/weather/<your-favorite-city>

Example:
curl http://127.0.0.1:8000/api/weather/denver

curl http://127.0.0.1:8000/api/weather/<your-favorite-zipcode>/<country-code-such-as-us>

Example:
curl http://127.0.0.1:8000/api/weather/98101/us

curl http://127.0.0.1:8000/api/weather/id/<your-favorite-city-id>

City id can be found here: http://bulk.openweathermap.org/sample/

Example:
curl http://127.0.0.1:8000/api/weather/id/833

探索Momento缓存集成

WeatherController.php中可以找到使用Momento的Laravel缓存客户端和缓存驱动的不同方式示例。

要查看直接使用Momento客户端的示例,请查看我们的PHP SDK 示例

以下提取了Momento的Laravel缓存驱动器的一个简单示例用法

$apiKey = env("WEATHER_API_KEY");
$url = "https://api.openweathermap.org/data/2.5/weather?q={$city}&appid={$apiKey}";
$result = Cache::get($city);
if (!is_null($result)) {
    return $result;
} else {
    $res = $this->httpClient->get($url);
    if ($res->getStatusCode() == 200) {
        $json = $res->getBody();
        // 10 minutes TTLc
        Cache::put($city, $json, 600);
        return $json;
    }
}