Java three classes implement memory cache

Source: Internet
Author: User

There is a requirement that was intended to be done with Redis, but found that the Redis list does not support a time-out setting.

So I wrote a simple cache with Java, the operation is similar to Redis, a total of only 3 classes:

Project Address: Https://github.com/newpanjing/group-cache.git

Project name: Group-cache

Simple memory cache implementation, the implementation of the group concept, a group is an orderly collection, set to support key-value expire to make up the Redis list of a total of 3 categories: groupcachefactory The factory is used to get Group group groups, hold multiple key and value cacheentity cache entities, and all cached data is cacheentity into group Test code:

Package Com.qikenet.cache;

Import Java.util.Random; public class Cachetest {public static void main (string[] args) {/** * concept: * Group caching, in traditional Redis, memcached this kind of cache 
     In the container, are the key-value type of * So-called group caching, that is, in the outer layer of the key-value with a logo * with a list for comparison, in Redis, the list structure is this, and the list of an item can not set the survival time: * ABC
     * 1 * 2 * 3 * * In the GROUPCACHE structure is this: * ABC * a 1 * b 2 5 * C 3 1 * The first line: A on behalf of key,1 on behalf of value,10 on behalf of the survival of 10 seconds, survival time in seconds///Create a factory, temporarily does not support the persistence groupcachefactory
    Factory=new groupcachefactory ();
    Gets a group Group1=factory.group ("Group1"); Group1.push ("A", 123);//default permanent surviving Group1.push ("B", 321, 10);/live 10 seconds/See how long it's been broken System.out.println (element B of Group 1

    Residual Expiration Time: "+group1.ttl (" B "));
    Whether the detection value exists SYSTEM.OUT.PRINTLN ("a exists:" +group1.exist ("a"));

    System.out.println ("C" exists: "+group1.exist" ("C"));

    Gets a valid key System.out.println ("group1 Keys:" +group1.getkeys ()); Get a valid value SystEm.out.println ("group1 Values:" +group1.getvalues ());


    Gets the value System.out.println via key ("Get through A:" +group1.getvalue ("a"));

    Gets a group and sets the capacity to 100, the default capacity is 1000, and the data in different groups cannot share group Group2=factory.group ("Group2", 100);
    If the push data is greater than the capacity, the for (int i=0;i<101;i++) {Group2.push (string.valueof (i), I, New Random (). Nextint (10)) is discarded;

    //Get the number of surviving elements System.out.println ("group2 Size:" +group2.size ());

    Set the survival time of the element Group2.expire ("2", 100);
    Deletes an element Group2.delete ("3");

    System.out.println ("group deleted element Size:" +group2.size ());

    Gets the group capacity size System.out.println ("group2 Capacity:" +group2.getcapacity ());

System.out.println (Group2.getkeys ()); }
}



Specific code:

Cache Factory:

Package Com.qikenet.cache;

Import Java.util.LinkedHashMap;
Import Java.util.Map;
Import Java.util.Random;

/**
 * Simple memory cache implementation, Implementation Group Concept,<br/>
 * A group inside is an ordered set,<br/>
 * Collection support key-value expire compensate Redis Lack of a list * * 
 @author panjing
 * @date August 6, 2016 morning 9:27:22
 * @project
 qikenet-group-cache
* * public class Groupcachefactory {

	//data container
	private map<string, object> container;

	Public Groupcachefactory () {
		container = new linkedhashmap<string, object> ();
	}

	/**
	 * If the group exists, it is created without existence, guaranteed not to be null
	 * 
	 @param key
	 * @return
	 /Public
	Group Group (String key, int capacity) {

		Group group = null;
		Object entry = Container.get (key);
		if (entry!= null) {
			group = (group) entry;
		} else {
			group = new Group (capacity);
			Container.put (key, group);
		}

		return group;
	}

	/**
	 * If the group exists, it is created, the default capacity 1000
	 * * 
	 @param key
	 * @return/public Group
	Group (String Key) {return

		This.group (key, 1000);
	}
}

Cache Group:

Package Com.qikenet.cache;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.concurrent.ArrayBlockingQueue; /** * Group operation, internal data orderly queue * * @author panjing * @date August 6, 2016 morning 9:33:34 * @project Qikenet-group-cache * @param <t&gt
 ;

	* * Public class Group {private arrayblockingqueue<cacheentity> queue;//cache queue private Integer capacity;
		public Group (int capacity) {queue = new arrayblockingqueue<cacheentity> (capacity);
	This.capacity = capacity;

		/** * Tail into * * @param object * @param second/public void push (String key, Object object, int second) {
	Put in the queue, Queue.offer (new Cacheentity (Key, Object, System.currenttimemillis (), second, this));
	/** * Tail into * * @param object */public void push (String key, Object object) {Push (Key, object, 0);
		/** * Returns and removes head out * * @return/Public Object poll () {cacheentity entity = Queue.poll (); If the expiration is exceeded, return NULL if (!ENTITY.ISEXPIRe ()) {return null;
	return Entity.getvalue ();
		/** * Returns the head element and puts it to the end * * @return/public Object Rpoll () {cacheentity entity = Queue.poll ();
		Returns null if (!entity.isexpire ()) {return NULL if the validity period is exceeded;
		The Object object = Entity.getvalue ();
		Queue.offer (entity);
	return object; /** * Search for a valid cache entity through key * * @param key * @return/Private cacheentity Find (String key) {synchronized (q
			Ueue) {iterator<cacheentity> iterator = Queue.iterator ();
				while (Iterator.hasnext ()) {cacheentity entity = Iterator.next ();
				if (Key.equals (Entity.getkey ())) {return entity;
		} return null; }/** * Delete key * * @param key */public void Delete (String key) {synchronized (queue) {cacheentity E
			Ntity = Find (key);
			if (entity!= null) {Queue.remove (entity); }}/** * gets * * @param key * @return/Public Object GetValue (String key) {cacheentity entit based on key
		y = Find (key); If (Entity!= null && entity.isexpire ())
		{return entity.getvalue ();
	return null; /** * Get a valid cache entity * * @return/private list<cacheentity> Getcacheentitys () {List<cacheentity&gt ;
		Keys = new arraylist<cacheentity> ();
		Iterator<cacheentity> iterator = Queue.iterator ();
			while (Iterator.hasnext ()) {cacheentity cacheentity = Iterator.next ();
			if (Cacheentity.isexpire ()) {Keys.add (cacheentity);
	} return keys; /** * Get Key list * * @return/public list<string> Getkeys () {list<string> keys = new Arraylis
		T<string> ();
		List<cacheentity> caches = Getcacheentitys ();
		for (cacheentity cacheentity:caches) {Keys.add (Cacheentity.getkey ());
	return keys; /** * Get Value List * * @return/public list<object> getValues () {list<object> values = new Arrayl
		Ist<object> ();
		List<cacheentity> caches = Getcacheentitys (); for (cacheentity Cacheentity:caches) {Values.add (Cacheentity.getvalue ());
	return values;  /** * View element survival time,-1 failure, 0 long-term effective * * @param key * @return/public int ttl (String key) {cacheentity entity
		= Find (key);
		if (entity!= null) {return Entity.ttl ();
	} return-1;
		/** * Returns the element of the head * * @return/Public Object Peek () {cacheentity entity = Queue.peek ();
		if (entity!= null) {return entity.getvalue ();
	return null; /** * Set Element survival time * * @param key * @param second/public void expire (String key, int second) {Cacheenti
		Ty entity = find (key);
			if (entity!= null) {Entity.settimestamp (System.currenttimemillis ());
		Entity.setexpire (second); }/** * see if key exists * * @param key * @return/public boolean exist (String key) {return find (key)!= n
	ull;
	/** * See if the group is empty * * @return/public Boolean isempty () {return queue.isempty (); /** * Gets the size of the surviving element * * @return/public int size () {return Getcacheentitys (). Size ();
	/** * Get capacity * * @return/public Integer getcapacity () {return capacity; }
}
Cache entity:

Package Com.qikenet.cache;

Import java.io.Serializable; /** * Cache Entity * * @author panjing * @date August 6, 2016 morning 9:33:25 * @project Qikenet-group-cache/public class Cacheenti

	Ty implements Serializable {private static final long serialversionuid = 2082223810638865724L; Private String key; Key private Object value;//value private long timestamp;//a time stamp stored when the cache is used to calculate whether the element expires private int expire = 0; Default long-term active private Group group;//container public cacheentity (String key, Object value, long timestamp, int expire, Group gro
		UP) {super ();
		This.key = key;
		This.value = value;
		This.timestamp = timestamp;
		This.expire = expire;
	This.group = Group;
	} public void Settimestamp (Long timestamp) {this.timestamp = timestamp;
	Public Long Gettimestamp () {return timestamp;
	Public String Getkey () {return key;
	public void Setkey (String key) {this.key = key;
	Public Object GetValue () {return value; } public void SetValue (Object value) {thiS.value = value;
	public int Getexpire () {return expire;
	The public void Setexpire (int expire) {this.expire = expire;
		/** * Get the remaining time * * @return/public int ttl () {if (This.expire = 0) {return this.expire;
	return This.expire-gettime ();
		/** * Get current time and element difference time * @return * * private int getTime () {if (This.expire = 0) {return this.expire;
		Long current = System.currenttimemillis ();
		Long value = Current-this.timestamp;
	return (int) (value/1000) + 1;
		/** * If * * @return * * * () {if (This.expire = 0) {return true;
			if (GetTime () > This.expire) {//Failed to remove the group.delete (key);
		return false;
	return true; }
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.