20221206

Beware of accumulating expired Octane cached items

When using swoole tables as Octane cache in Laravel, be aware that the expired cached items are never really deleted. 


The get method of the cache ignores the expired items but they are never flushed if you don't explicitly delete them. 

To avoid the Swoole Cache table to grow ad aeternum you must do some cleanup from time to time.
Define a new class that will do the clean up every minute using the Tick functionality of the Swoole extension. 

<?php

namespace xxxxxx;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Laravel\Octane\Facades\Octane;
use Illuminate\Support\Facades\App;

class CacheHouseKeeping {

public static function clean () {
  $table=App::make('octane.cacheTable');
    $i=$deleted=0;
    Log::info("** Current date=".date('Y-m-d H:i:s')." expiring old cached items");
    foreach ($table as $key => $record) {
    if ($record['expiration']<time()) {
Log::debug("EXPIRING key=$key value=".$record['value'].' expiration='.date('Y-m-d H:i:s', $record['expiration']));
        $table->del($key);
        $deleted++;
      }
      $i++;
    }
    Log::info("** Total keys scanned $i, deleted=$deleted remaining=".($i-$deleted)." finished ".date('Y-m-d H:i:s'));
  }
public static function boot() {
  Octane::tick('cache-housekeeping-ticker', fn () => self::getAndReport())
    ->seconds(60);
  }
}


And in the file app/Providers/RouteServiceProvider.php call the boot method of the class in order to set the Ticker. 
if ($record['expiration']<time()) {

No hay comentarios: