NCache provides facility of Tags which acts as an identifying mark for the cache items. By Using tags user can Associate one or more keywords with cache objects. Therefore, one can get and remove items on the basis of Tags.
Include the following import statement in your project before using Tags:
import com.alachisoft.ncache.runtime.caching.*;
Following code example explains how to use Tags:
Initialize cache and tags:
// Initialization Cache and Defining Tags
Cache _cache = NCache.initializeCache("Cache");
Object value = "Can contain any type";
Tag[] tagList = new Tag[6];
tagList[0] = new Tag("tag1");
tagList[1] = new Tag("tag2");
tagList[2] = new Tag("tag3");
tagList[3] = new Tag("tag4");
tagList[4] = new Tag("tag5");
tagList[5] = new Tag("tag6");
Add items to cache containing tags:
// Adding items having Tags
_cache.add("Key1", value, tagList);
_cache.add("Key2", value, tagList);
_cache.add("Key3", value, tagList);
Get keys from cache containing tag:
// Continuing previous...
// Here you can get keys having tags by three different methods.
Collection keys = _cache.getKeysByTag(tagList[0]);
Collection keys = _cache.getKeysByAllTags(tagList);
Collection keys = _cache.getKeysByAnyTag(tagList);
Get items from cache containing tag:
// Continuing previous...
// Here you can get items having tags by three different methods.
HashMap tagHashMap = _cache.getByTag(tagList[0]);
HashMap tagHashMap = _cache.getByAllTags(tagList);
HashMap tagHashMap = _cache.getByAnyTag(tagList);
Remove items from cache containing tag:
// Continuing previous ...
// Here you can remove items having tags by three different methods.
_cache.removeByTag(tagList[0]);
_cache.removeByAllTags(tagList);
_cache.removeByAnyTag(tagList);
See Also