编程

Laravel 缓存

346 2024-10-08 17:25:00

缓存就像把你最喜欢的玩具放在玩具箱的顶部,这样你就可以在想玩的时候快速抓住它。

同样,Laravel 中使用缓存来存储数据,这样你的网站就可以快速显示数据,而无需再次搜索或查询。就像更快地找到你的玩具一样,缓存可以帮助网站更快地加载。

Laravel 中缓存如何使用

Laravel 中有一个称之为缓存(cache)内置的存储。它帮你存储数据并能在之后快速获取。

在缓存中存储数据

比如 - 天气数据。天气信息不会在每次请求时都发生改变,因此就没必要每次都调用 DB 或者 API。将其保存在缓存中是会更有效:

use Illuminate\Support\Facades\Cache;

$weatherData = getWeatherFromService();

Cache::put('current_weather', $weatherData, now()->addMinutes(60));

此处,current_weather 是缓存键名,$weatherData 是缓存信息,然后是到期时间(DateTime 实例或者表示秒数的整型值)。

检索并检查数据

从缓存中获取天气数据:

$weatherData = Cache::get('current_weather');

检查数据是否还存在:

if (Cache::has('current_weather')) {
    // It's there!
}

从缓存中删除数据

要刷新天气数据,请移除旧的信息:

Cache::forget('current_weather');

缓存可以做的事

  • 对于繁忙的博客或在线商店,缓存帖子和产品以提高速度:
// Fetching paginated blog posts/products with caching:
public function index()
{    
    $page = request()->get('page', 1);

    $cacheKey = 'blog_page_' . $page;// unique key for each posts page
    $posts = Cache::remember($cacheKey, 3600, function () {
        return Post::paginate(10);
    });

    $cacheKey = 'products_page_' . $page; // unique key for each products page
    $products = Cache::remember($cacheKey, 3600, function () {
        return Product::paginate(10);
    });
}

// Remember to remove cache when a new product is created, updated or destroyed.
public function store(Request $request){
    $product = Product::create($request->all());

    // Clear the cache for all pages
    $totalPages = ceil(Product::count() / 10);
    for ($i = 1; $i <= $totalPages; $i++) {
        Cache::forget('products_page_' . $i);
    }    
}
  • 缓存频繁请求的 API 响应,以减少负载并缩短响应时间:
public function getWeatherData($city)
{
    $cacheKey = 'weather_' . $city;

    $weatherData = Cache::remember($cacheKey, 3600, function () use ($city) {
        $response = Http::get('https://api.weatherapi.com/v1/current.json',['key' => 'your_api_key', 'q' => $city]);

        return $response->json();
    });

    return $weatherData;
}
  • 缓存用于生成仪表板指标的高开销查询
public function getDashboardMetrics()
{
    $cacheKey = 'dashboard_metrics';

    $metrics = Cache::remember($cacheKey, 3600, function () {
        return [
            $monthlySales = Order::selectRaw('MONTH(created_at) as month, COUNT(*) as total_orders, SUM(total) as total_revenue')->whereYear('created_at', date('Y'))->groupBy(DB::raw('MONTH(created_at)'))->orderBy('month')->get(),
            $userRegistrations = User::selectRaw('MONTH(created_at) as month, COUNT(*) as total_registrations')->whereYear('created_at', date('Y'))->groupBy(DB::raw('MONTH(created_at)'))->orderBy('month')->get(),
            $topProducts = Product::select('products.id', 'products.name')->join('order_product', 'order_product.product_id', '=', 'products.id')->join('orders', 'orders.id', '=', 'order_product.order_id')->selectRaw('COUNT(order_product.product_id) as total_sold, SUM(order_product.price * order_product.quantity) as total_revenue')->groupBy('products.id', 'products.name')->orderByDesc('total_sold')->take(5)->get(),
            $averageOrderValue = Order::selectRaw('MONTH(created_at) as month, AVG(total) as avg_order_value')->whereYear('created_at', date('Y'))->groupBy(DB::raw('MONTH(created_at)'))->orderBy('month')->get(),
            // ...
        ];
    
    });

    return $metrics;
}
  • 缓存频繁访问的数据,如设置或配置、产品类别或导航菜单
public function getSetting($key)
{
    $cacheKey = 'setting_' . $key;
    $setting = Cache::rememberForever($cacheKey, function () use ($key) {
        return Setting::where('key', $key)->first();
    });

    return $setting ? $setting->value : null;
}

public function getCategories()
{
    $cacheKey = 'categories';

    $categories = Cache::remember($cacheKey, 86400, function () {
        return Category::all();
    });

    return $categories;
}
  • 通过模型事件自动无效缓存。可以在 EventServiceProvider.php 中注册。
public function boot()
{
    Order::created(function () {
        Cache::forget('dashboard_metrics');
    });

    User::created(function () {
        Cache::forget('dashboard_metrics');
    });

    Product::updated(function () {
        Cache::forget('dashboard_metrics');
    });
		
}

总结

Laravel 中的缓存通过实现存储数据的快速访问,使网站更快。