Skip to content
龙卷锋 edited this page Apr 17, 2020 · 9 revisions

Cache

1. General Cache

Support: memory & redis

step1. To configure cache

application.conf

memory:

cache.enabled = true
cache.adapter = memory
cache.prefix = cache:
cache.expire = 3600
cache.useSecondLevelCache = false

redis:

cache.enabled = true
cache.adapter = redis
cache.prefix = cache:
cache.expire = 3600
cache.useSecondLevelCache = false

# Redis
redis.enabled = true
redis.prefix = app:
redis.host = 127.0.0.1
redis.port = 6379
redis.database = 0
redis.password = 
redis.timeout = 0

setp2. How to use

module app.TestCache;

import hunt.framework;

class TestCache
{
    void set()
    {
        // Set string
        Application.instance().cache().set("test", "1", 60);

        // Set Struct
        TestStruct testStruct;
        testStruct.id = 1;
        testStruct.name = "test";
        Application.instance().cache().set("testStruct", testStruct, 60);
    }

    void get()
    {
        string str = Application.instance().cache().get("test");
        TestStruct testStruct = Application.instance().cache().get!TestStruct("testStruct");
    }

    void has()
    {
        bool isExist1 = Application.instance().cache().hasKey("test");
        bool isExist2 = Application.instance().cache().hasKey("testStruct");
    }

    void remove()
    {
        bool isSuccess1 = Application.instance().cache().remove("test");
        bool isSuccess2 = Application.instance().cache().remove("testStruct");
    }
}

struct TestStruct
{
    int id;
    string name;
}

2. Redis Pool

step1. To configure redis

# Redis
redis.enabled = true
redis.prefix = app:
redis.host = 127.0.0.1
redis.port = 6379
redis.database = 0
redis.password = 
redis.timeout = 0

# Redis pool
redis.pool.enabled = true
redis.pool.maxWait = 5000
redis.pool.maxIdle = 50
redis.pool.minIdle = 5

step2. How to use cahe

module app.RedisCache;

import hunt.framework;
import hunt.Long;

class RedisCache
{
    void set()
    {
        Application.instance().redis().set("test", "1");
        Application.instance().redis().expire("test", 60);
        Long result = Application.instance().redis().setnx("test1", "success");
        result.longValue();// result 1
        Long result1 = Application.instance().redis().setnx("test1", "success");
        result1.longValue();// result 0
    }

    void get()
    {
        string str = Application.instance().redis().get("test");
        Long result = Application.instance().redis().ttl("test");
        result.longValue(); // ttl second
    }
}
Clone this wiki locally