A simple example of Redis caching

Source: Internet
Author: User
Tags constructor hash json log log redis redis server

As a result of a systematic study of Redis, Redis is used as the data cache in multiple projects in the company, so take advantage of these days to write a demo of the time, here for your own later study notes, if there is wrong place, please tap bricks.

The Redis website recommended to Java use a lot of clients: Jedis, Redisson, Jredis, Jdbc-redis, of course, the most preferred is Jedis; You can refer to the Redis client website.

Next, my demo, my case is not a redis that is integrated through spring, and this will be covered in the demo later.

(1). Create a Maven hero, introduce the Jedis client in the project's Pom, and rely on spring management, so we also introduce spring-related jar packages.

<span style= "White-space:pre" >		</span><dependency>
				<groupid>redis.clients</ groupid>
				<artifactId>jedis</artifactId>
				<version>${jedis-version}</version>
			</dependency>
		<dependency>

(2). Generally one (System) project uses the Redis server multi-node cluster server, so it will be the (Jedis) Redis client encapsulation, because this example I write a single node, but I still according to multi-node thinking of the client package.

Redisclient class

/** * Redis Client Package * @author Leo * */public class Redisclient {/** * log record */private static final log log = Lo
	Gfactory.getlog (Redisclient.class);
	
	/** * Redis Connection Pool */private jedispool pool;
	public void Setpool (Jedispool pool) {this.pool = pool;
		}/** * Get Jedis * @return */public Jedis getresource () {Jedis Jedis =null;
		try {Jedis =pool.getresource ();
		} catch (Exception e) {log.info ("can ' t get the Redis resource");
	} return Jedis;
	}/** * Close connection * @param Jedis */public void disconnect (Jedis Jedis) {jedis.disconnect ();
				/** * return Jedis to Connection pool * @param Jedis */public void Returnresource (Jedis Jedis) {if (null! = Jedis) {try {
			Pool.returnresource (Jedis);
			} catch (Exception e) {log.info ("can ' t return Jedis to Jedispool"); }}}/** * cannot return Jedispool, release Jedis client object, * @param Jedis */public void Brokenresource (Jedis Jedis) {if (jedis!
			=null) {try {pool.returnbrokenresource (Jedis); } CAtch (Exception e) {log.info ("can ' t release Jedis Object");
 }
		}
	}
}
The connection pool, and connection pool parameter configuration, and redisclient dependency injection are then managed through spring's bean.xml.

<!--Jedis Connection Pool configuration parameters:--<bean id= "Poolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "maxactive" value= "+" ></property> <property name= "Maxidle" "value=" ></p roperty> <property name= "maxwait" value= "15000" ></property> <property name= "Testonborrow" value= "f Alse "></property> <property name=" Testonreturn "value=" false "></property> </bean> <!-  -Jedis Connection Pool connection local Redis service builder injected--<bean id= "Pool" class= "Redis.clients.jedis.JedisPool" > <constructor-arg index= "0" ref= "poolconfig"/> <constructor-arg index= "1" value= "10.224.68.46"/> <constructor-arg Inde x= "2" value= "6379"/> <constructor-arg index= "3" value= "$"/> </bean> <!--cleint--> <b Ean id= "redisclient" class= "com.deppon.cache.redis.RedisClient" > <property name= "Pool" ref= "Pool"/> </be An> 
(3). After creating the redisclient, I'm going to create a memory, a tool container for redis operations. Because it is a public container, I create an interface is not a container interface should be closed, should be Kaifeng, to ensure that the database is stored in the type of the polymorphism of the object.

Memory Interface:

/**
 * 
 * @author Leo
 * Cache Storage Interface
 * @param <K> Key
 * @param <V> value
*/Public Interface Rediscachestorage<k, v> {
	/**
	 * Insert key  and value
	 * @param key * In the Redis database
	 @param Value
	 * @return
	 *
	/Boolean set (K key,v value);
	/**
	 * Insert key and value in the Redis database  and set expiration time
	 * @param key
	 * @param value
	 * @param exp Expiry time s
	 * @re Turn
	 *
	/Boolean set (K key, V value, int exp);
	/**
	 * Get value
	 * @param key
	 * @return *
	/V Get (K key)
	based on key to Redis; /**
	 * Delete data from Redis library
	 * @param key
	 * @return *
	/boolean remove (K key);
	/**
	 * Set Hash type data to Redis database
	 * @param cacheKey can be seen as a table
	 * @param key table	field
	 * @param value  
	 * @ return
	 *
	/Boolean hset (String cachekey,k key,v value);
	/**
	 * Gets the value of the hash table data type
	 * @param cacheKey
	 * @param key
	 * @return *
	/V hget (String cachekey,k key);
	/**
	 * Gets the data of the hash type
	 * @param cacheKey
	 * @return *
	/map<k,v> hget (String cacheKey);
and the storage implementation class:

/** * Redis Cache Memory Implementation * @author Leo * @param <V> * * Public class Rediscachestorageimpl<v> implements Redi Scachestorage<string, v> {/** * log record */public static final log log = Logfactory.getlog (Rediscachestorageimpl
	. Class);
	/** * Redis Client */private redisclient redisclient; 
	
	/** * Default Stale time */private static final int exprie_time =3600*24;
	public void Setredisclient (Redisclient redisclient) {this.redisclient = redisclient;  /** * Insert key and value in Redis database * @param key * @param value * @return */@Override public boolean set (String
	Key, V value) {//Set default stale time return set (key, value, Exprie_time); /** * Insert key and value in the Redis database and set expiration time * @param key * @param value * @param exp Expiry time S * @return */@Supp
		Resswarnings ("finally") @Override public boolean set (String key, V value, int exp) {Jedis Jedis =null;
		Converts key and value to JSON object String Jkey =cacheutils.tojsonstring (key); String Jvalue =cacheutils.tojSonstring (value);
		Whether the operation was successful Boolean issucess =true;
			if (Stringutils.isnotempty (Jkey)) {Log.info ("key is empty");
		return false;
			try {//Get Client Object Jedis =redisclient.getresource ();
		Perform insert Jedis.setex (Jkey, exp, jvalue);
			} catch (Jedisexception e) {log.info ("client can ' t connect server");
			Issucess =false;
			if (null!=jedis) {//Releases Jedis object Redisclient.brokenresource (Jedis);
		} return false;
			}finally{if (issucess) {//Return connection Pool Redisclient.returnresource (Jedis);
		} return true; }}/** * Get value * @param key * @return */@SuppressWarnings ("unchecked") @Override public V g based on key to Redis
		ET (String key) {Jedis Jedis =null;
		Converts key and value to JSON object String Jkey =cacheutils.tojsonstring (key);
		V Jvalue =null;
			Key cannot be null if (Stringutils.isempty (Jkey)) {Log.info ("key is empty");
		return null;
			try {//Get Client Object Jedis =redisclient.getresource ();
			Executes the query String value = Jedis.get (Jkey); Determine if the valueNon-null if (Stringutils.isempty (value)) {return null;
			}else{jvalue= (V) cacheutils.jsonparseobject (value);
		}//Return connection Pool Redisclient.returnresource (Jedis);
			} catch (Jedisexception e) {log.info ("client can ' t connect server");
			if (null!=jedis) {//Releases Jedis object Redisclient.brokenresource (Jedis);
	}} return jvalue; }/** * Delete data from Redis library * @param key * @return */@SuppressWarnings ("finally") @Override public boolean remove (St
		Ring key) {Jedis Jedis =null;
		Converts key and value to JSON object String Jkey =cacheutils.tojsonstring (key);
		Whether the operation was successful Boolean issucess =true;
			if (Stringutils.isempty (Jkey)) {Log.info ("key is empty");
		return false;
			} try {Jedis =redisclient.getresource ();
		Execute Delete jedis.del (Jkey);
			} catch (Jedisexception e) {log.info ("client can ' t connect server");
			Issucess =false;
			if (null!=jedis) {//Releases Jedis object Redisclient.brokenresource (Jedis);
		} return false;
		}finally{if (issucess) {		Return connection Pool Redisclient.returnresource (Jedis);
		} return true; }}/** * Set hash type data to redis database * @param cacheKey can be seen as a table * @param key table field * @param value * @return */@Supp
		Resswarnings ("finally") @Override public boolean Hset (string CacheKey, String key, V value) {Jedis Jedis =null;
		Converts key and value to JSON object String Jkey =cacheutils.tojsonstring (key);
		String Jcachekey =cacheutils.tojsonstring (CacheKey);
		String jvalue =cacheutils.tojsonstring (value);
		Whether the operation was successful Boolean issucess =true;
			if (Stringutils.isempty (Jcachekey)) {Log.info ("CacheKey is empty");
		return false;
			} try {Jedis =redisclient.getresource ();
		Performs an insert hash Jedis.hset (Jcachekey, Jkey, Jvalue);
			} catch (Jedisexception e) {log.info ("client can ' t connect server");
			Issucess =false;
			if (null!=jedis) {//Releases Jedis object Redisclient.brokenresource (Jedis);
		} return false;
			}finally{if (issucess) {//Return connection Pool Redisclient.returnresource (Jedis);
			}return true;
	}}/** * Gets the value of the hash table data type * @param cacheKey * @param key * @return */@SuppressWarnings ("unchecked") @Override
		Public V Hget (string CacheKey, String key) {Jedis Jedis =null;
		Converts key and value to JSON object String Jkey =cacheutils.tojsonstring (key);
		String Jcachekey =cacheutils.tojsonstring (CacheKey);
		V Jvalue =null;
			if (Stringutils.isempty (Jcachekey)) {Log.info ("CacheKey is empty");
		return null;
			try {//Get Client Object Jedis =redisclient.getresource ();
			Executes the query String value = Jedis.hget (Jcachekey, Jkey);
			Determines whether the value is non-null if (Stringutils.isempty (value)) {return null;
			}else{jvalue= (V) cacheutils.jsonparseobject (value);
		}//Return connection Pool Redisclient.returnresource (Jedis);
			} catch (Jedisexception e) {log.info ("client can ' t connect server");
			if (null!=jedis) {//Releases Jedis object Redisclient.brokenresource (Jedis);
	}} return jvalue; /** * Gets the data of the hash type * @param cacheKey * @return */@Override public map<String, v> Hget (String cacheKey) {string Jcachekey =cacheutils.tojsonstring (CacheKey);
			Non-null Check if (Stringutils.isempty (Jcachekey)) {Log.info ("CacheKey is empty!");
		return null;
		} Jedis Jedis =null;
		map<string,v> result =null;
			try {Jedis =redisclient.getresource (); 
			
			Get List collection map<string,string> Map = Jedis.hgetall (Jcachekey);  if (null!=map) {for (map.entry<string, string> entry:map.entrySet ()) {if (result ==null) {result =new
					Hashmap<string,v> (); } result.put (String) Cacheutils.jsonparseobject (Entry.getkey ()), (V) Cacheutils.jsonparseobject (Entry.getvalue ())
				);
			}}} catch (Jedisexception e) {log.info ("client can ' t connect server");
			if (null!=jedis) {//Releases Jedis object Redisclient.brokenresource (Jedis);
	}} return result; }

}
(4), the next step is to write a specific business userservice, to test the use of Redis memory in the specific business, that is, the implementation of (non-relational database persistence operation). The example in this example is the operation of the user in the current project

To create a userentity entity class:

/**
 * User entity class
 * @author Leo
 * * *
 /Public
class Userentity {
	//user ID
	private String userId;
	User account
	private String empcode;
	User name
	private String empname;
	User role
	private String role;
	Position
	private String title;
	Public String getUserId () {
		return userId;
	}
	public void Setuserid (String userId) {
		This.userid = userId;
	}
	Public String Getempcode () {
		return empcode;
	}
	public void Setempcode (String empcode) {
		empcode = empcode;
	}
	Public String Getempname () {
		return empname;
	}
	public void Setempname (String empname) {
		empname = empname;
	}
	Public String Getrole () {
		return role;
	}
	public void Setrole (String role) {
		this.role = role;
	}
	Public String GetTitle () {
		return title;
	}
	public void Settitle (String title) {
		this.title = title;
	}
Then create a business-level service for the user operation, and because this is primarily a test of nosql data persistence, the operation of the database Persistence layer (DAO) is ignored.

Userserviceimpl class:

/** * Business Layer Interface Implementation * @author Leo * */public class Userserviceimpl implements Iuserservice {private static final String
	CacheKey = "Userentity";
	
	/** * Cache Storage */private rediscachestorageimpl<userentity> Storagecache;
	public void Setstoragecache (rediscachestorageimpl<userentity> storagecache) {this.storagecache = StorageCache; }/** * Added * @param entity * @return */@Override public boolean adduserentity (userentity entity) {//Non-empty if (Entity ==null | |
		Stringutils.isempty (Entity.getuserid ())) {return false;
		}/** * Do a database persistence, there is no need to declare the */System.out.println ("Insert Database First,.........");
	Then do the non-relational database persistence return Storagecache.hset (CacheKey, Entity.getuserid (), entity);
	} @Override public Boolean deleteuserentity (userentity entity) {return false;
		*/** * Based on ID query * @return * * @Override public userentity Queryuserentitybyuserid (userentity userentity) {//Non-empty if (userentity ==null | | Stringutils.isempty (Userentity.getuserid ())) {return null;
		}//go to cache to see if the query exists, does not exist in query userentity Reslut = Storagecache.hget (CacheKey, Userentity.getuserid ());
		if (reslut!=null) {return reslut;
		}else{//Query database SYSTEM.OUT.PRINTLN ("Query Database");
	} return null;
 }

}
And the management of the Spring-bean.xml configuration to the business layer:

<!--storge Cache memory--
		<bean id= "Storagecache" class= " Com.deppon.cache.storage.impl.RedisCacheStorageImpl ">
			<property name=" redisclient "ref=" redisclient "/ >
		</bean>
		<bean id= "Userserviceimpl" class= "Com.deppon.cache.service.impl.UserServiceImpl" >
			<property name= "Storagecache" ref= "Storagecache"/>
		</bean>
(6). Finally write a junit test to see if there is any inserted into the Redis library

public class Testuserserviceimpl {/** * user interface */private iuserservice Userserviceimpl;
	public void Setuserserviceimpl (Iuserservice userserviceimpl) {This.userserviceimpl = Userserviceimpl; } @Before public void SetUp () throws Exception {Userserviceimpl = (iuserservice) springtesthelper.get (). Getbeanbyclas
	S (userserviceimpl.class); } @After public void TearDown () throws Exception {} @Test public void Testadd () {userentity entity = new Userenti
		Ty ();
		Entity.setuserid ("000001");
		Entity.setempcode ("130566");
		Entity.setempname ("Leonardo-zeng");
		Entity.setrole ("Java development Engineer");
		Entity.settitle ("PM");
		Boolean isTrue =userserviceimpl.adduserentity (entity);
	Assert.asserttrue (isTrue);
		} @Test public void Testquerybyid () {userentity entity = new userentity ();
		Entity.setuserid ("000001");
		Userentity userentity =userserviceimpl.queryuserentitybyuserid (entity);
	System.out.println (userentity); }
}
Connect to the Redis library and query it for a value that exists in the library

Redis 127.0.0.1:6379> Hkeys "\" userentity\ ""
1) "\" 000001\ ""
Redis 127.0.0.1:6379> hget "\" userentity\ "" "\" 000001\ ""
"{\" @type \ ": \" com.deppon.cache.entity.userentity\ ", \" empcode\ ": \" 130566\ ", \" Empn
Ame\ ": \" leonardo-zeng\ ", \" role\ ": \" Java development engineer\ ", \" title\ ": \" Pm\ ",
\ "userid\": \ "000001\"} "
Redis 127.0.0.1:6379>
This is the whole demo.




Related Article

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.