Redis (2) using Jedis to implement Redis in Java

Source: Internet
Author: User

Redis was installed in the Windows environment yesterday.

Below you are ready to test the use of Redis in a Java project.

The Redis website recommends using Jedis to access Redis. So first the Jedis jar package is prepared, and the jar packages that need to be relied upon.

commons-pool2-2.3

hamcrest-core-1.3

Jedis-2.7.2.jar

Because Redis also belongs to a database and access to data, so put him on the DAO layer, separate from the service

ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool;ImportCom.dyuproject.protostuff.LinkedBuffer;ImportCom.dyuproject.protostuff.ProtostuffIOUtil;ImportCom.dyuproject.protostuff.runtime.RuntimeSchema;Importcom.xhxkj.ssm.entity.UserEntity;/*** Access to the Redis data layer *@authorXX **/ Public classRedisdao {Private FinalJedispool Jedispool;//Redis Connection Pooling        /*** Construction Method *@paramIP -Access IP *@paramports accessed by Port*/     PublicRedisdao (String IP,intPort) {Jedispool=NewJedispool (Ip,port); }        //Create a schema to serialize    Privateruntimeschema<userentity> schema = Runtimeschema.createfrom (userentity.class); /*** Get user information for Redis in user name *@paramUsername entered by username *@returnpresence return: This object, does not exist return: null*/     Publicuserentity GetUser (String username) {//Redis Operations        Try{Jedis Jedis=Jedispool.getresource (); Try {                //when storing in Redis, key writing rules, official recommendation, object: Object Properties//that is, get the value using "User:username" as the key.String key = "User:" +username; //Custom Serialization//The value obtained in Redis must be a byte array that needs to be converted to a Java object by deserialization                byte[] bytes =Jedis.get (Key.getbytes ()); if(Bytes! =NULL)                {                    //gets an empty objectUserentity user =Schema.newmessage (); //put in user after deserializationprotostuffioutil.mergefrom (bytes, user, schema); returnuser; }            }finally{jedis.close (); }        }Catch(Exception e) {e.printstacktrace (); }        return NULL; }            /*** Store the user object in the cache *@paramUser *@returnsuccessful return "OK"; failure return error message*/     PublicString putuser (userentity user) {Try{Jedis Jedis=Jedispool.getresource (); Try {                //Store the user object with the corresponding keyString key = "User:" +User.getusername (); //custom serialization operations, using Protostuff to serialize objects into byte arrays                byte[] bytes =Protostuffioutil.tobytearray (user, schema, linkedbuffer.allocate (linkedbuffer.default_buffer_                                SIZE)); //The cache time is 1 hours, and the cache time is counted in seconds .                intTimeout = 60*60; //store This object in Redis                returnJedis.setex (Key.getbytes (), timeout,bytes); } finally{jedis.close (); }        } Catch(Exception e) {e.printstacktrace (); }        return NULL; }}

Here are two methods, put and get, which need to use serialization and deserialization operations, the JAR package has the following several

Protostuff-core-1.0.8.jar

Protostuff-runtime-1.0.8.jar

Protostuff-collectionschema-1.0.8.jar

Protostuff-api-1.0.8.jar

Protostuff belongs to a very good performance

Configuring in Spring

<!--Redisdao--
<bean id= "Redisdao" class= "Com.xxx.dao.redis.RedisDao" >
<constructor-arg index= "0" value= "localhost"/>
<constructor-arg index= "1" value= "6379"/>
</bean>

You can then invoke the Redisdao method directly at the service layer.

First go to Redis for the presence of cached user information
Userentity Resultuser = Redisdao.getuser ("xx");
If it does not exist, then place a user information in the cache
if (Resultuser = = null)
{
String result = redisdao.putuser (user);
SYSTEM.OUT.PRINTLN (result);
return null;
}
Else
{
return resultuser;
}

It is important to note that if the store succeeds, the return is a string "OK"

Make sure that your Redis service is turned on and that the CMD window is open before use

Because many of the network above are configured with Maven, so the jar package is difficult to find, the dependencies between the jar is really troublesome, recommend a website http://maven.outofmemory.cn/

This site can be very good to find a variety of jar packages, and tell you the relationship of dependence, very convenient

Redis (2) using Jedis to implement Redis in Java

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.