-
-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathtcache.cpp
127 lines (108 loc) · 2.67 KB
/
tcache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* Copyright (c) 2019, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include "tcachefactory.h"
#include "tcachestore.h"
#include <TAppSettings>
#include <TCache>
#include <TWebApplication>
/*!
\class TCache
\brief The TCache class stores items so that can be served faster.
*/
TCache::TCache()
{
static int CacheGcProbability = TAppSettings::instance()->value(Tf::CacheGcProbability).toInt();
_gcDivisor = CacheGcProbability;
if (Tf::app()->cacheEnabled()) {
_cache = TCacheFactory::create(Tf::app()->cacheBackend());
if (_cache) {
if (!_cache->open()) {
tError() << "Failed to open cache. Check the settings of cache.ini.";
TCacheFactory::destroy(Tf::app()->cacheBackend(), _cache);
_cache = nullptr;
}
}
} else {
tWarn() << "Cache not available. Check the settings of application.ini such as 'Cache.SettingsFile' and 'Cache.Backend'.";
}
}
TCache::~TCache()
{
if (_cache) {
_cache->close();
TCacheFactory::destroy(Tf::app()->cacheBackend(), _cache);
}
}
void TCache::initialize()
{
if (_cache) {
_cache->init();
}
}
void TCache::cleanup()
{
if (_cache) {
_cache->cleanup();
}
}
/*!
Stores a new item with the \a key and a \a value in the cache and sets the
timeout after a given number of \a seconds.
*/
bool TCache::set(const QByteArray &key, const QByteArray &value, int seconds)
{
bool ret = false;
if (_cache) {
if (compressionEnabled()) {
ret = _cache->set(key, Tf::lz4Compress(value), seconds);
} else {
ret = _cache->set(key, value, seconds);
}
// GC
if (_gcDivisor > 0 && Tf::random(1, _gcDivisor) == 1) {
_cache->gc();
}
}
return ret;
}
/*!
Returns the value associated with the \a key.
*/
QByteArray TCache::get(const QByteArray &key)
{
QByteArray value;
if (_cache) {
value = _cache->get(key);
if (compressionEnabled()) {
value = Tf::lz4Uncompress(value);
}
}
return value;
}
/*!
Removes the item that have the \a key from the cache.
*/
void TCache::remove(const QByteArray &key)
{
if (_cache) {
_cache->remove(key);
}
}
/*!
Removes all items from the cache.
*/
void TCache::clear()
{
if (_cache) {
_cache->clear();
}
}
bool TCache::compressionEnabled()
{
static bool compression = Tf::appSettings()->value(Tf::CacheEnableCompression).toBool();
return compression;
}