Showing entries with tag "cache".

Found 3 entries

Linux: Disable DNS cache in systemd

New Linux distributions are enabling local DNS caching. For most users this is a sane default, but as a system administrator this can sometimes get in the way. You can check if your local cache is running and see the statistics with:

resolvectl statistics

Which will tell you how active your cache is, what the hit/miss ratio is, and information about DNSSEC. If you need to clear your local cache you can run:

resolvectl flush-caches

Doing this repeatedly can get cumbersome if you are testing remote DNS frequently. If you want to disable local caching all together you can run:

systemctl disable systemd-resolved.service --now

Remember to update your /etc/resolv.conf to point at the correct DNS server after you're done.

Leave A Reply

PHP: Serializing data to save it for caching

I need to cache some data to disk between PHP requests so I decided to compare the various methods available.

Using 100000 element array as source data

Serialize save: 2.958 ms (1.5M)
Serialize read: 5.447 ms

JSON save: 1.880 ms (574.96K)
JSON read: 6.876 ms

PHP save: 8.684 ms (1.7M)
PHP read: 26.863 ms

Memcache set: 5.651 ms
Memcache get: 2.465 ms

IGBinary save: 1.377 ms (720.08K)
IGBinary read: 2.245 ms

MsgPack save: 1.389 ms (359.92K)
MsgPack read: 2.930 ms

I was surprised to see IGBinary and MsgPack so much faster than native JSON. JSON is easy and super portable, but not the fastest.

Leave A Reply

Perl: Simple file cache

I need a simple disk based object cache and Cache::File was overkill. I wrote my own dependency free (only core modules) version:

cache($key);                     # Get
cache($key, $val);               # Set expires is 1 hour (default)
cache($key, $val, time() + 900); # Set expires in 15 minutes
cache($key, undef)               # Delete

I purposely wrote it small so it can be copy/pasted in to other scripts simply. I wrote a more robust implementation with some basic tests as well. When an entry is fetched that is expired it will be removed from disk. Abandoned cache entries will persist on disk until cache_clean() is called.

sub cache {
    use JSON::PP; use Tie::File; use File::Path; use Digest::SHA qw(sha256_hex);

    my ($key, $val, $expire, $ret, @data) = @_;

    my $hash = sha256_hex($key || "");
    my $dir  = "/dev/shm/perl-cache/" . substr($hash, 0, 3);
    my $file = "$dir/$hash.json";
    mkpath($dir);

    tie @data, 'Tie::File', $file or die("Unable to write $file"); # to r/w file

    if (@_ > 1) { # Set
        $data[0] = encode_json({ expires => int($expire || 3600), data => $val, key => $key });
    } elsif ($key && -r $file) { # Get
        eval { $ret = decode_json($data[0]); };
        if ($ret->{expires} && $ret->{expires} > time()) {
            $ret = $ret->{data};
        } else {
            unlink($file);
            $ret = undef;
        }
    }

    return $ret;
}
Leave A Reply