KHolder.m 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 @"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 "KUtil.h"
  15. @interface KHolder ()
  16. // 正在进行归档的状态位
  17. @property (assign, atomic) BOOL archiving;
  18. @property (assign, atomic) BOOL cleaning;
  19. @property (strong, nonatomic) NSFileManager *fileManager;
  20. @property (strong, atomic) NSMutableArray *keys;
  21. @property (assign, nonatomic) NSUInteger size;
  22. @property (strong, nonatomic) NSMutableDictionary *objects;
  23. @property (strong, nonatomic) NSString *path;
  24. @property (strong, atomic) NSConditionLock *lock;
  25. // 把数据写到磁盘
  26. - (void)doArchive;
  27. - (void)archiveData;
  28. - (void)archiveAllData;
  29. - (void)doClean;
  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. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  64. [self doArchive];
  65. });
  66. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  67. [self doClean];
  68. });
  69. return self;
  70. }
  71. return nil;
  72. }
  73. #pragma mark - private
  74. - (NSFileManager *)fileManager
  75. {
  76. return [NSFileManager defaultManager];
  77. }
  78. - (void)doArchive
  79. {
  80. NSTimer *archivingTimer = [NSTimer timerWithTimeInterval:10.f target:self selector:@selector(archiveData) userInfo:nil repeats:YES];
  81. NSRunLoop *archivingRunloop = [NSRunLoop currentRunLoop];
  82. [archivingRunloop addTimer:archivingTimer forMode:NSDefaultRunLoopMode];
  83. while (YES) {
  84. [archivingRunloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:2.f]];
  85. }
  86. }
  87. - (void)archiveData
  88. {
  89. self.archiving = YES;
  90. NSLog(@"archiging...");
  91. if (0 < ARCHIVING_THRESHOLD
  92. && ARCHIVING_THRESHOLD < self.size) {
  93. BOOL isDirectory = NO;
  94. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  95. [self.fileManager createDirectoryAtPath:self.self.path
  96. withIntermediateDirectories:YES
  97. attributes:nil
  98. error:nil];
  99. }
  100. [self.lock lockWhenCondition:DATA_FREE];
  101. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  102. while (0 < [copiedKeys count]) {
  103. // 归档至阈值一半的数据
  104. if ((ARCHIVING_THRESHOLD / 2) >= self.size) {
  105. break;
  106. }
  107. NSString *key = [copiedKeys lastObject];
  108. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  109. NSData *data = [self.objects objectForKey:key];
  110. [data writeToFile:filePath atomically:YES];
  111. self.size -= data.length;
  112. [copiedKeys removeLastObject];
  113. [self.objects removeObjectForKey:key];
  114. }
  115. copiedKeys = nil;
  116. [self.lock unlockWithCondition:DATA_FREE];
  117. }
  118. self.archiving = NO;
  119. }
  120. - (void)archiveAllData
  121. {
  122. self.archiving = YES;
  123. BOOL isDirectory = NO;
  124. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  125. [self.fileManager createDirectoryAtPath:self.self.path
  126. withIntermediateDirectories:YES
  127. attributes:nil
  128. error:nil];
  129. }
  130. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  131. while (0 < [copiedKeys count]) {
  132. NSString *key = [copiedKeys lastObject];
  133. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  134. NSData *data = [self.objects objectForKey:key];
  135. [data writeToFile:filePath atomically:YES];
  136. self.size -= data.length;
  137. [copiedKeys removeLastObject];
  138. [self.objects removeObjectForKey:key];
  139. }
  140. copiedKeys = nil;
  141. self.archiving = NO;
  142. }
  143. - (void)doClean
  144. {
  145. NSTimer *cleaningTimer = [NSTimer timerWithTimeInterval:30.f target:self selector:@selector(cleanExpiredObjects) userInfo:nil repeats:YES];
  146. NSRunLoop *cleaningRunloop = [NSRunLoop currentRunLoop];
  147. [cleaningRunloop addTimer:cleaningTimer forMode:NSDefaultRunLoopMode];
  148. while (YES) {
  149. [cleaningRunloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:2.f]];
  150. }
  151. }
  152. - (void)cleanExpiredObjects
  153. {
  154. NSLog(@"cleaning...");
  155. self.cleaning = YES;
  156. if (self.keys && 0 < [self.keys count]) {
  157. [self.lock lock];
  158. for (int i = 0; i < [self.keys count] - 1; i ++) {
  159. NSString *tmpKey = [self.keys objectAtIndex:i];
  160. KObject *leftObject = [self objectForKey:tmpKey];
  161. if ([leftObject expiredTimestamp] < [KUtil nowTimestamp]) {
  162. [self removeObjectForKey:tmpKey];
  163. }
  164. else {
  165. break;
  166. }
  167. }
  168. [self.lock unlockWithCondition:DATA_FREE];
  169. }
  170. self.cleaning = NO;
  171. }
  172. #pragma mark - public
  173. - (void)removeObjectForKey:(NSString *)key {
  174. [self.keys removeObject:key];
  175. if ([[self.objects allKeys] containsObject:key]) {
  176. [self.objects removeObjectForKey:key];
  177. }
  178. else {
  179. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  180. [self.fileManager removeItemAtPath:filePath error:nil];
  181. }
  182. }
  183. - (void)setValue:(id)value forKey:(NSString *)key expiredAfter:(NSInteger)duration
  184. {
  185. KObject *object = [[KObject alloc] initWithData:value andLifeDuration:duration];
  186. if (self.archiving) {
  187. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  188. [object.data writeToFile:filePath atomically:YES];
  189. }
  190. else {
  191. [self.objects setValue:object.data forKey:key];
  192. self.size += [object size];
  193. }
  194. // TODO sort the key by expired time.
  195. [self.keys removeObject:key];
  196. [self.lock lockWhenCondition:DATA_FREE];
  197. for (int i = [self.keys count] - 1; i >= 0; i --) {
  198. NSString *tmpKey = [self.keys objectAtIndex:i];
  199. KObject *leftObject = [self objectForKey:tmpKey];
  200. // 过期时间越晚
  201. if ([leftObject expiredTimestamp] <= [object expiredTimestamp]) {
  202. if (([self.keys count] - 1) == i) {
  203. [self.keys addObject:key];
  204. }
  205. else {
  206. [self.keys insertObject:key atIndex:i + 1];
  207. }
  208. break;
  209. }
  210. }
  211. [self.lock unlockWithCondition:DATA_FREE];
  212. if (! [self.keys containsObject:key]) {
  213. [self.keys insertObject:key atIndex:0];
  214. }
  215. // 超过阈值,归档
  216. if ((! self.archiving)
  217. && 0 < ARCHIVING_THRESHOLD
  218. && ARCHIVING_THRESHOLD < self.size) {
  219. [self archiveData];
  220. }
  221. }
  222. - (id)valueForKey:(NSString *)key
  223. {
  224. KObject *object = [self objectForKey:key];
  225. if (object && ! [object expired]) {
  226. return [object value];
  227. }
  228. // No such object.
  229. return nil;
  230. }
  231. - (KObject *)objectForKey:(NSString *)key
  232. {
  233. if (! [[self.objects allKeys] containsObject:key]) {
  234. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  235. if ([self.fileManager fileExistsAtPath:filePath isDirectory:NO]) {
  236. // 超过阈值直接返回,不装入内存
  237. if ((! self.archiving) && 0 < ARCHIVING_THRESHOLD && ARCHIVING_THRESHOLD < self.size) {
  238. return [[KObject alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];
  239. }
  240. else {
  241. NSData *data = [NSData dataWithContentsOfFile:filePath];
  242. [self.objects setValue:data forKey:key];
  243. self.size += data.length;
  244. data = nil;
  245. [self.fileManager removeItemAtPath:filePath error:nil];
  246. }
  247. }
  248. else {
  249. return nil;
  250. }
  251. }
  252. return [[KObject alloc] initWithData:[self.objects objectForKey:key]];
  253. }
  254. // Convert object to NSDictionary.
  255. - (NSDictionary *)serialize
  256. {
  257. [self archiveAllData];
  258. return [NSDictionary dictionaryWithObjectsAndKeys:
  259. self.keys, @"keys",
  260. [NSString stringWithFormat:@"%d", self.size], @"size",
  261. nil];
  262. }
  263. // Convert NSDictionary to object.
  264. - (void)unserializeFrom:(NSDictionary *)dict
  265. {
  266. if ([[dict allKeys] containsObject:@"keys"]
  267. && [[dict allKeys] containsObject:@"meta"]) {
  268. self.keys = [dict objectForKey:@"keys"];
  269. self.size = [[dict objectForKey:@"size"] intValue];
  270. }
  271. }
  272. @end