momentohq / laravel-example
展示Momento缓存驱动器的Laravel天气应用程序。
Requires
- php: ^8.0.2
- guzzlehttp/guzzle: ^7.5
- momentohq/laravel-cache: v1.0.5
- dev-main
- v0.3.2
- v0.3.1
- v0.3.0
- v0.2.3
- v0.2.2
- v0.2.1
- v0.2.0
- v0.1.0
- dev-chore/update-example-version
- dev-release
- dev-chore/update-api-key
- dev-fix/dockerfile
- dev-feat/update-php-sdk
- dev-atomic-increment
- dev-grpc-fork-test
- dev-laravel-cache-version-bump-1-0-1
- dev-update-docker-0-2-2
- dev-chore/add-dockerfile
- dev-fix/github-wrokflows
- dev-feat/move-files-from-personal-repo
This package is auto-updated.
Last update: 2024-09-27 18:50:00 UTC
README
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_name
和default_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; } }