ForgeTotal.js 5
it

Total.js 5

Mettere valori in cache in memoria

Total.js 5 · total5@0.0.19 cacheperformance Eseguita con Total.js 5

CACHE è un archivio chiave-valore in memoria con scadenza. CACHE.set(key, value, expire) salva un valore (la scadenza è un testo come '10 seconds' o '5 minutes', predefinito '5 minutes'). CACHE.get(key, default) restituisce il valore, o il valore predefinito una volta scaduto. CACHE.remove(key) elimina una chiave e CACHE.reset(search) elimina ogni chiave che contiene il testo.

Usalo per risultati costosi da calcolare che possono essere un po' datati. La cache vive nel processo: viene svuotata al riavvio e non è condivisa tra processi.

controllers/cache.js
exports.install = function() {
	ROUTE('GET /slow/', slow);
	ROUTE('DELETE /slow/', clear);
};

var computed = 0;

function slow($) {

	var cached = CACHE.get('slow-result');

	if (cached) {
		$.json({ value: cached, cached: true, computed: computed });
		return;
	}

	computed++;
	var value = 'result-' + computed;
	CACHE.set('slow-result', value, '1 second');
	$.json({ value: value, cached: false, computed: computed });
}

function clear($) {
	CACHE.remove('slow-result');
	$.json({ ok: true });
}