feat: Add factory method for in-memory caches

Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
This commit is contained in:
Christoph Wurst 2023-10-11 13:29:21 +02:00
parent 04db454e9f
commit ff672b11e2
No known key found for this signature in database
GPG Key ID: CC42AC2A7F0E56D8
3 changed files with 32 additions and 0 deletions

View File

@ -31,6 +31,7 @@
*/
namespace OC\Memcache;
use OCP\Cache\CappedMemoryCache;
use OCP\Profiler\IProfiler;
use OCP\ICache;
use OCP\ICacheFactory;
@ -184,6 +185,10 @@ class Factory implements ICacheFactory {
return $this->distributedCacheClass !== self::NULL_CACHE;
}
public function createInMemory(int $capacity = 512): ICache {
return new CappedMemoryCache($capacity);
}
/**
* Check if a local memory cache backend is available
*

View File

@ -75,4 +75,20 @@ interface ICacheFactory {
* @since 13.0.0
*/
public function createLocal(string $prefix = ''): ICache;
/**
* Create an in-memory cache instance
*
* Useful for remembering values inside one process. Cache memory is cleared
* when the object is garbage-collected. Implementation may also expire keys
* earlier when the TTL is reached or too much memory is consumed.
*
* Cache keys are local to the cache object. When building two in-memory
* caches, there is no data exchange between the instances.
*
* @param int $capacity maximum number of cache keys
* @return ICache
* @since 28.0.0
*/
public function createInMemory(int $capacity = 512): ICache;
}

View File

@ -140,4 +140,15 @@ class FactoryTest extends \Test\TestCase {
$profiler = $this->getMockBuilder(IProfiler::class)->getMock();
new \OC\Memcache\Factory('abc', $logger, $profiler, $localCache, $distributedCache);
}
public function testCreateInMemory(): void {
$logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
$profiler = $this->getMockBuilder(IProfiler::class)->getMock();
$factory = new \OC\Memcache\Factory('abc', $logger, $profiler, null, null, null);
$cache = $factory->createInMemory();
$cache->set('test', 48);
self::assertSame(48, $cache->get('test'));
}
}