1 module hunt.framework.provider.CacheServiceProvider;
2 
3 import hunt.framework.provider.ServiceProvider;
4 import hunt.framework.config.ApplicationConfig;
5 
6 import hunt.cache.CacheFactory;
7 import hunt.cache.Cache;
8 import hunt.cache.CacheOptions;
9 import hunt.cache.Defined;
10 import hunt.logging;
11 import hunt.redis.RedisPoolOptions;
12 
13 import hunt.framework.Init;
14 
15 import poodinis;
16 
17 import core.time;
18 
19 /**
20  * 
21  */
22 class CacheServiceProvider : ServiceProvider {
23 
24     override void register() {
25         container.register!Cache.initializedBy({
26             ApplicationConfig config = container.resolve!ApplicationConfig();
27             ApplicationConfig.CacheConf cacheConf = config.cache;
28             ApplicationConfig.RedisConf redisConf = config.redis;
29             auto redisPoolOptions = redisConf.pool;
30 
31             CacheOptions options = new CacheOptions();
32             options.adapter = cacheConf.adapter;
33             options.prefix = cacheConf.prefix;
34             options.useSecondLevelCache = cacheConf.useSecondLevelCache;
35             options.maxEntriesLocalHeap = cacheConf.maxEntriesLocalHeap;
36             options.eternal = cacheConf.eternal;
37             options.timeToIdleSeconds = cacheConf.timeToIdleSeconds;
38             options.timeToLiveSeconds = cacheConf.timeToLiveSeconds;
39             options.overflowToDisk = cacheConf.overflowToDisk;
40             options.diskPersistent = cacheConf.diskPersistent;
41             options.diskExpiryThreadIntervalSeconds = cacheConf.diskExpiryThreadIntervalSeconds;
42             options.maxEntriesLocalDisk = cacheConf.maxEntriesLocalDisk;
43 
44             if(cacheConf.adapter == AdapterType.REDIS || cacheConf.adapter == AdapterType.REDIS_CLUSTER) {
45 
46                 if(!redisConf.enabled) {
47                     throw new Exception("The Redis is disabled.");
48                 }
49 
50                 RedisPoolOptions poolConfig = new RedisPoolOptions();
51                 poolConfig.host = redisConf.host;
52                 poolConfig.port = cast(int) redisConf.port;
53                 poolConfig.password = redisConf.password;
54                 poolConfig.database = cast(int) redisConf.database;
55                 poolConfig.soTimeout = cast(int) redisPoolOptions.idleTimeout;
56                 poolConfig.connectionTimeout =  redisConf.timeout;
57                 poolConfig.waitTimeout = msecs(redisPoolOptions.waitTimeout);
58                 poolConfig.size = redisPoolOptions.maxPoolSize;
59 
60                 version(HUNT_DEBUG) infof("Initializing Cache Service: %s", poolConfig.toString());
61 
62                 options.redisPool = poolConfig;
63                 options.redisCluster.nodes = redisConf.cluster.nodes;
64             } 
65             
66             return CacheFactory.create(options);
67         }).singleInstance();
68     }
69 }