sys = require('sys');
/*** Helper implementation*/
function helper() {
console. log('HELPER CREATED');this. name = 'helper';
/*** Object creation*/this. onCreate = function() {console. log('DATA CREATED');
return {'scheme' : 'helper','data' : 'TEST','ttl' : new Date(). getTime() + 2000,'hits' : 0};};
/*** Object deletion*/
this. onDelete = function(obj) {console. log('DATA DELETED ' + sys. inspect(obj));
/*** Maybe implemented in async mode*///
process. nextTick(function() {// console. log('TEST 1 finished');// });};};
/*** Cache implementation*/
function cache() {this. helpers = {};
this. data = {};
console. log('CACHE CREATED');
this. addHelper = function(obj) {console. log('CACHE HELPER ADDED');this. helpers[obj. name] = obj;};
/*** return object from cache if exeist if not create it proto* get({methodName: '', params: ''})*/
this. get = function(key) {console. log('GET OBJECT: ' + key. methodName);
/*** We can use msgpack for more speed*/
var obj = this. data[JSON. stringify(key)];
if (obj == undefined) {var helper = this. helpers[key. methodName];
if (helper != null) {obj = helper. onCreate(key. params);
this. set(key, obj);}}if (obj != null)obj. hits++;return obj;};
/*** store object in cache*/
this. set = function(key, obj) {console. log('SET OBJECT: ' + key);
/*** We can use msgpack for more speed*/
this. data[JSON. stringify(key)] = obj;};
/*** cache cleaner*/this. purge = function() {ttl = new Date(). getTime();
for ( var key in this. data) {var obj = this. data[key];
if ((obj != undefined) && (obj. ttl != 0) && (obj. ttl < ttl)) {
/*** We can use msgpack for more speed*/
var helper = this. helpers[JSON. parse(key). methodName];
if (helper != null) {helper. onDelete(obj);console. log('PURGE ' + ttl);}delete this. data[key];}}};
var that = this;
/*** Need set interval*/setInterval(function() {that. purge();}, 1000 * 1 * 1);};
/*** TEST*/
var app_cache = new cache();
var app_helper = new helper();
app_cache. addHelper(app_helper);var obj = app_cache. get({'methodName' : 'helper',params : ''});
obj = app_cache. get({'methodName' : 'helper',params : ''});
sys. puts(sys. inspect(obj));setInterval(function() {var obj = app_cache. get({'methodName' : 'helper',params : ''});
sys. puts(sys. inspect(obj));}, 1000 * 15 * 1);
Вот и все. Мы получили очень быстрое хранилище объектов с полным жизненным циклом: учетом времени жизни, метаданными, автоматическим созданием и смертью объекта.