Kernel::System::Cache

NAME

Kernel::System::Cache – Key/value based data cache for OTRS

DESCRIPTION

This is a simple data cache. It can store key/value data both in memory and in a configured cache backend for persistent caching.

This can be controlled via the config settings Cache::InMemory and Cache::InBackend. The backend can also be selected with the config setting Cache::Module and defaults to file system based storage for permanent caching.

CACHING STRATEGY

Caching works based on CacheTypes and CacheKeys.

CACHE TYPES

For file based caching, a CacheType groups all contained entries in a top level directory like var/tmp/CacheFileStorable/MyCacheType. This means also that all entries of a specific CacheType can be deleted with one function call, "CleanUp()".

Typically, every backend module like Kernel::System::Valid has its own CacheType that is stored in $Self for consistent use. There could be exceptions when modules have much cached data that needs to be cleaned up together. In this case additional CacheTypes could be used, but this should be avoided.

CACHE KEYS

A CacheKey is used to identify a single cached entry within a CacheType. The specified cache key will be internally hashed to a file name that is used to fetch/store that particular cache entry, like var/tmp/CacheFileStorable/Valid/2/1/217727036cc9b1804f7c0f4f7777ef86.

It is important that all variables that lead to the output of different results of a function must be part of the CacheKey if the entire function result is to be stored in a separate cache entry. For example, "StateGet()" in Kernel::System::State allows fetching of States by Name or by ID. So there are different cache keys for both cases:

    my $CacheKey;
    if ( $Param{Name} ) {
        $CacheKey = 'StateGet::Name::' . $Param{Name};
    }
    else {
        $CacheKey = 'StateGet::ID::' . $Param{ID};
    }

Please avoid the creation of too many different cache keys, as this can be a burden for storage and performance of the system. Sometimes it can be helpful to implement a function like the one presented above in another way: StateGet() could call the cached StateList() internally and fetch the requested entry from its result. This depends on the amount of data, of course.

CACHING A BACKEND MODULE

Define a CacheType and a CacheTTL.

Every module should have its own CacheType which typically resembles the module name. The CacheTTL defines how long a cache is valid. This depends on the data, but a value of 30 days is considered a good default choice.

Add caching to methods fetching data.

All functions that list and fetch entities can potentially get caches.

Implement cache cleanup.

All functions that add, modify or delete entries need to make sure that the cache stays consistent. All of these operations typically need to cleanup list method caches, while only modify and delete affect individual cache entries that need to be deleted.

Whenever possible, avoid calling "CleanUp()" for an entire cache type, but instead delete individual cache entries with "Delete()" to keep as much cached data as possible.

It is recommendable to implement a _CacheCleanup() method in the module that centralizes cache cleanup.

Extend module tests.

Please also extend the module tests to work on non-cached and cached values (e. g. calling a method more than one time) to ensure consistency of both cached and non-cached data, and proper cleanup on deleting entities.

PUBLIC INTERFACE

new()

Don't use the constructor directly, use the ObjectManager instead:

    my $CacheObject = $Kernel::OM->Get('Kernel::System::Cache');

Configure()

change cache configuration settings at runtime. You can use this to disable the cache in environments where it is not desired, such as in long running scripts.

please, to turn CacheInMemory off in persistent environments.

    $CacheObject->Configure(
        CacheInMemory  => 1,    # optional
        CacheInBackend => 1,    # optional
    );

Set()

store a value in the cache.

    $CacheObject->Set(
        Type  => 'ObjectName',      # only [a-zA-Z0-9_] chars usable
        Key   => 'SomeKey',
        Value => 'Some Value',
        TTL   => 60 * 60 * 24 * 20, # seconds, this means 20 days
    );

The Type here refers to the group of entries that should be cached and cleaned up together, usually this will represent the OTRS object that is supposed to be cached, like 'Ticket'.

The Key identifies the entry (together with the type) for retrieval and deletion of this value.

The TTL controls when the cache will expire. Please note that the in-memory cache is not persistent and thus has no TTL/expiry mechanism.

Please note that if you store complex data, you have to make sure that the data is not modified in other parts of the code as the in-memory cache only refers to it. Otherwise also the cache would contain the modifications. If you cannot avoid this, you can disable the in-memory cache for this value:

    $CacheObject->Set(
        Type  => 'ObjectName',
        Key   => 'SomeKey',
        Value => { ... complex data ... },

        TTL            => 60 * 60 * 24 * 1,  # optional, default 20 days
        CacheInMemory  => 0,                 # optional, defaults to 1
        CacheInBackend => 1,                 # optional, defaults to 1
    );

Get()

fetch a value from the cache.

    my $Value = $CacheObject->Get(
        Type => 'ObjectName',       # only [a-zA-Z0-9_] chars usable
        Key  => 'SomeKey',
    );

Please note that if you store complex data, you have to make sure that the data is not modified in other parts of the code as the in-memory cache only refers to it. Otherwise also the cache would contain the modifications. If you cannot avoid this, you can disable the in-memory cache for this value:

    my $Value = $CacheObject->Get(
        Type => 'ObjectName',
        Key  => 'SomeKey',

        CacheInMemory => 0,     # optional, defaults to 1
        CacheInBackend => 1,    # optional, defaults to 1
    );

Delete()

deletes a single value from the cache.

    $CacheObject->Delete(
        Type => 'ObjectName',       # only [a-zA-Z0-9_] chars usable
        Key  => 'SomeKey',
    );

Please note that despite the cache configuration, Delete and CleanUp will always be executed both in memory and in the backend to avoid inconsistent cache states.

CleanUp()

delete parts of the cache or the full cache data.

To delete the whole cache:

    $CacheObject->CleanUp();

To delete the data of only one cache type:

    $CacheObject->CleanUp(
        Type => 'ObjectName',   # only [a-zA-Z0-9_] chars usable
    );

To delete all data except of some types:

    $CacheObject->CleanUp(
        KeepTypes => ['Object1', 'Object2'],
    );

To delete only expired cache data:

    $CacheObject->CleanUp(
        Expired => 1,   # optional, defaults to 0
    );

Type/KeepTypes and Expired can be combined to only delete expired data of a single type or of all types except the types to keep.

Please note that despite the cache configuration, Delete and CleanUp will always be executed both in memory and in the backend to avoid inconsistent cache states.

PurgeTrash()

Flush the trash directory if possible, as this method is just available on FileStorable.

Scroll to Top