KHolder.m 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. //
  2. // KHolder.m
  3. // KacheDemo
  4. //
  5. // Created by jiajun on 7/25/12.
  6. // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
  7. //
  8. #define Kache_Objects_Disk_Path @"Caches/Kache_objects"
  9. #define DATA_FREE 0
  10. #define DATA_OPERATING 1
  11. #import "KConfig.h"
  12. #import "KHolder.h"
  13. #import "KObject.h"
  14. #import "KPool.h"
  15. #import "KQueue.h"
  16. #import "KUtil.h"
  17. @interface KHolder ()
  18. // 正在进行归档的状态位
  19. @property (assign, atomic) BOOL archiving;
  20. @property (assign, atomic) BOOL cleaning;
  21. @property (strong, nonatomic) NSFileManager *fileManager;
  22. @property (strong, atomic) NSMutableArray *keys;
  23. @property (assign, nonatomic) NSUInteger size;
  24. @property (strong, nonatomic) NSMutableDictionary *objects;
  25. @property (strong, nonatomic) NSString *path;
  26. @property (strong, atomic) NSConditionLock *lock;
  27. // 把数据写到磁盘
  28. - (void)archiveData;
  29. - (void)archiveAllData;
  30. - (void)cleanExpiredObjects;
  31. @end
  32. @implementation KHolder
  33. @synthesize archiving = _archiving;
  34. @synthesize cleaning = _cleaning;
  35. @synthesize fileManager = _fileManager;
  36. // 缓存Key列表
  37. @synthesize keys = _keys;
  38. // 缓存大小
  39. @synthesize size = _size;
  40. // 缓存内容
  41. @synthesize objects = _objects;
  42. @synthesize path = _path;
  43. #pragma mark - init
  44. - (id)init
  45. {
  46. self = [self initWithToken:@"_KacheDefault"];
  47. if (self) {
  48. return self;
  49. }
  50. return nil;
  51. }
  52. - (id)initWithToken:(NSString *)token
  53. {
  54. self = [super init];
  55. if (self) {
  56. self.objects = [[NSMutableDictionary alloc] init];
  57. self.keys = [[NSMutableArray alloc] init];
  58. self.size = 0;
  59. self.lock = [[NSConditionLock alloc] initWithCondition:DATA_OPERATING];
  60. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
  61. NSString *libDirectory = [paths objectAtIndex:0];
  62. self.path = [libDirectory stringByAppendingPathComponent:[Kache_Objects_Disk_Path stringByAppendingPathExtension:token]];
  63. return self;
  64. }
  65. return nil;
  66. }
  67. #pragma mark - private
  68. - (NSFileManager *)fileManager
  69. {
  70. return [NSFileManager defaultManager];
  71. }
  72. - (void)archiveData
  73. {
  74. self.archiving = YES;
  75. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  76. BOOL isDirectory = NO;
  77. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  78. [self.fileManager createDirectoryAtPath:self.self.path
  79. withIntermediateDirectories:YES
  80. attributes:nil
  81. error:nil];
  82. }
  83. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  84. [self.lock lockWhenCondition:DATA_FREE];
  85. while (0 < [copiedKeys count]) {
  86. // 归档至阈值一半的数据
  87. if ((ARCHIVING_THRESHOLD / 2) >= self.size) {
  88. break;
  89. }
  90. NSString *key = [copiedKeys lastObject];
  91. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  92. NSData *data = [self.objects objectForKey:key];
  93. [data writeToFile:filePath atomically:YES];
  94. self.size -= data.length;
  95. [copiedKeys removeLastObject];
  96. [self.objects removeObjectForKey:key];
  97. }
  98. [self.lock unlockWithCondition:DATA_FREE];
  99. copiedKeys = nil;
  100. self.archiving = NO;
  101. });
  102. }
  103. - (void)archiveAllData
  104. {
  105. self.archiving = YES;
  106. BOOL isDirectory = NO;
  107. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  108. [self.fileManager createDirectoryAtPath:self.self.path
  109. withIntermediateDirectories:YES
  110. attributes:nil
  111. error:nil];
  112. }
  113. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  114. while (0 < [copiedKeys count]) {
  115. NSString *key = [copiedKeys lastObject];
  116. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  117. NSData *data = [self.objects objectForKey:key];
  118. [data writeToFile:filePath atomically:YES];
  119. self.size -= data.length;
  120. [copiedKeys removeLastObject];
  121. [self.objects removeObjectForKey:key];
  122. }
  123. copiedKeys = nil;
  124. self.archiving = NO;
  125. }
  126. - (void)cleanExpiredObjects
  127. {
  128. self.cleaning = YES;
  129. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  130. if (self.keys && 0 < [self.keys count]) {
  131. [self.lock lock];
  132. for (int i = 0; i < [self.keys count] - 1; i ++) {
  133. NSString *tmpKey = [self.keys objectAtIndex:i];
  134. KObject *leftObject = [self objectForKey:tmpKey];
  135. if ([leftObject expiredTimestamp] < [KUtil nowTimestamp]) {
  136. [self removeObjectForKey:tmpKey];
  137. }
  138. else {
  139. break;
  140. }
  141. }
  142. [self.lock unlockWithCondition:DATA_FREE];
  143. }
  144. self.cleaning = NO;
  145. });
  146. }
  147. #pragma mark - public
  148. - (void)removeObjectForKey:(NSString *)key {
  149. [self.keys removeObject:key];
  150. if ([[self.objects allKeys] containsObject:key]) {
  151. [self.objects removeObjectForKey:key];
  152. }
  153. else {
  154. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  155. [self.fileManager removeItemAtPath:filePath error:nil];
  156. }
  157. }
  158. - (void)setValue:(id)value forKey:(NSString *)key expiredAfter:(NSInteger)duration
  159. {
  160. KObject *object = [[KObject alloc] initWithData:value andLifeDuration:duration];
  161. if (self.archiving) {
  162. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  163. [object.data writeToFile:filePath atomically:YES];
  164. }
  165. else {
  166. [self.objects setValue:object.data forKey:key];
  167. self.size += [object size];
  168. }
  169. // TODO sort the key by expired time.
  170. [self.keys removeObject:key];
  171. if (! self.cleaning && (0 < [self.keys count])) {
  172. [self cleanExpiredObjects];
  173. [self.lock lockWhenCondition:DATA_FREE];
  174. for (int i = [self.keys count] - 1; i >= 0; i --) {
  175. NSString *tmpKey = [self.keys objectAtIndex:i];
  176. KObject *leftObject = [self objectForKey:tmpKey];
  177. // 过期时间越晚
  178. if ([leftObject expiredTimestamp] <= [object expiredTimestamp]) {
  179. if (([self.keys count] - 1) == i) {
  180. [self.keys addObject:key];
  181. }
  182. else {
  183. [self.keys insertObject:key atIndex:i + 1];
  184. }
  185. break;
  186. }
  187. }
  188. [self.lock unlockWithCondition:DATA_FREE];
  189. }
  190. if (! [self.keys containsObject:key]) {
  191. [self.keys insertObject:key atIndex:0];
  192. }
  193. // 超过阈值,归档
  194. if ((! self.archiving)
  195. && 0 < ARCHIVING_THRESHOLD
  196. && ARCHIVING_THRESHOLD < self.size) {
  197. [self archiveData];
  198. }
  199. }
  200. - (id)valueForKey:(NSString *)key
  201. {
  202. KObject *object = [self objectForKey:key];
  203. if (object && ! [object expired]) {
  204. return [object value];
  205. }
  206. // No such object.
  207. return nil;
  208. }
  209. - (KObject *)objectForKey:(NSString *)key
  210. {
  211. if (! [[self.objects allKeys] containsObject:key]) {
  212. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  213. if ([self.fileManager fileExistsAtPath:filePath isDirectory:NO]) {
  214. // 超过阈值直接返回,不装入内存
  215. if ((! self.archiving) && 0 < ARCHIVING_THRESHOLD && ARCHIVING_THRESHOLD < self.size) {
  216. return [[KObject alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];
  217. }
  218. else {
  219. NSData *data = [NSData dataWithContentsOfFile:filePath];
  220. [self.objects setValue:data forKey:key];
  221. self.size += data.length;
  222. data = nil;
  223. [self.fileManager removeItemAtPath:filePath error:nil];
  224. }
  225. }
  226. else {
  227. return nil;
  228. }
  229. }
  230. return [[KObject alloc] initWithData:[self.objects objectForKey:key]];
  231. }
  232. // Convert object to NSDictionary.
  233. - (NSDictionary *)serialize
  234. {
  235. [self archiveAllData];
  236. return [NSDictionary dictionaryWithObjectsAndKeys:
  237. self.keys, @"keys",
  238. [NSString stringWithFormat:@"%d", self.size], @"size",
  239. nil];
  240. }
  241. // Convert NSDictionary to object.
  242. - (void)unserializeFrom:(NSDictionary *)dict
  243. {
  244. if ([[dict allKeys] containsObject:@"keys"]
  245. && [[dict allKeys] containsObject:@"meta"]) {
  246. self.keys = [dict objectForKey:@"keys"];
  247. self.size = [[dict objectForKey:@"size"] intValue];
  248. }
  249. }
  250. @end