Jedis and spring integration and simple use of redistemplate operations

Source: Internet
Author: User

Sort out the integration of Redis with spring. and using Redistemplate. The first is to import the jar required by spring. Of course there are Jedis-2.1.0.jar,commons-pool-1.5.4.jar,spring-data-redis-1.0.0.release.jar (this is the version I used, should not be new)

1. After importing these jars, start organizing the configuration files:

The first is Web. Xml. This is still the same old way: paste it

<context-param>        <param-name>contextConfigLocation</param-name>        <param-value> classpath:applicationcontext*.xml</param-value>    </context-param>    <listener>        < listener-class>org.springframework.web.context.contextloaderlistener</listener-class >    </listener>

There is also the spring configuration file, everyone will see it. I'm still called Applicationcontext.xml,

<?xml version= "1.0" encoding= "Utf-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Util= "Http://www.springframework.org/schema/util" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp//Www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-2.5.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-2.5.xsdhttp//Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd"default-lazy-init=" false "><!--support annotations--<context:annotation-config/> <!--components Scan--<context:component-scan base- Package= "Com.demo"/> <context:property-placeholder location= "classpath:redis.properties"/> <bean id= "Jedispoo Lconfig "class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "maxactive" value= "${redis.pool.maxactive}"/> <property name= "Maxidle" value= "${redis.pool.maxidle}"/> <property name= "maxwait" value= "${redis.pool. maxwait} "/> <property name=" Testonborrow "value=" ${redis.pool.testonborrow} "/> </bean> <b Ean id= "Jedisconnectionfactory"class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" > <property name= "hostName" value= "${redis.ip}"/> <property name= "port" value= "${redis.port}"/> <property name= "Poolconfig" ref= "Jedispoolconfig"/> </bean> <bean id= "template"class= "Org.springframework.data.redis.core.RedisTemplate" > <property name= "connectionfactory" ref= " Jedisconnectionfactory "/> </bean> <bean id=" Userdao "class= "Com.demo.spring.UserDaoImpl" > <property name= "template" ref= "template"/> </bean> </beans >

There is another one is the redis.properties:

#最大分配的对象数  redis.pool.maxActive=1024  #最大能够保持idel状态的对象数  redis.pool.maxIdle=200   #当池内没有返回对象时, if the maximum wait time  redis.pool.maxWait=1000  #当调用borrow The object method, the validity check  is performed Redis.pool.testOnBorrow=true    #IP  redis.ip=127.0.0.1  #Port  Redis.port=6379

Well, the configuration file is these, and nothing special.

2. Write a user class:

 Public classUserImplementsSerializable {/**     *      */    Private Static Final LongSerialversionuid = -1530813282496676263l; PrivateInteger ID; PrivateString name;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}

3. Writing a Userdao and Userdaoimpl

 Public Interface Userdao {    void  Save (user user);    User Read (user user);    
 Public classUserdaoimplImplementsUserdao {PrivateRedistemplate<serializable, serializable>template;  PublicRedistemplate<serializable, serializable>gettemplate () {returntemplate; }     Public voidSetTemplate (redistemplate<serializable, serializable>template) {         This. Template =template; }     PublicUser Read (FinalUser User) {//User User2 = (user) Template.execute (new rediscallback<object> () {//@Override//Public User Doinredis (redisconnection connection) throws DataAccessException {//byte[] key = Template.getstringserializer (). Serialize ("id" +user.getid ());//if (connection.exists (key)) {//byte[] value = Connection.get (key);//String name = Template.getstringserializer (). Deserialize (value);//User User1 = new user ();//user1.setname (name);//return user1;//                }//return null;//            }//        });Valueoperations<serializable, serializable> opsforvalue =Template.opsforvalue (); User User2=(User) Opsforvalue.get (User.getid ()); returnUser2; }     Public voidSaveFinalUser User) {//Template.execute (New rediscallback<object> () {//Public Object Doinredis (redisconnection connection) throws DataAccessException {//Connection.set (Template.getstringserializer (). Serialize ("id" +user.getid ()), Template.getstringserializ ER (). Serialize (User.getname ()));//return null;//            }//        });valueoperations<serializable, serializable> opsforvalue =Template.opsforvalue ();    Opsforvalue.set (User.getid (), user); }}

The comment section here is another method, and it is also possible that the custom object needs to serialize Template.getstringserializer (). Serialize ("xxx");

There are many connection methods in comments such as:

Connection.mget (keys);//byte[] ... keys
Connection.mset (tuple);//map<byte[], byte[]> tuple
Connection.lset (key, index, value);//byte[] key, long index, byte[] Value
Connection.lrange (key, begin, end);//byte[] key, long begin, long end) and so on

4. Finally, the test class

PrivateApplicationContext app; PrivateUserdao Userdao;  PublicUserdao Getuserdao () {returnUserdao; }     Public voidSetuserdao (Userdao Userdao) { This. Userdao =Userdao; } @Before Public voidBefore ()throwsException {app=NewClasspathxmlapplicationcontext ("Applicationcontext.xml");
Get Userdao Object Userdao= (Userdao) app.getbean ("Userdao"); } @Test Public voidtest1 () {String name= "Fu"; User User=NewUser (); User.setname (name); User.setid (1); Userdao.save (user); System.out.println ("============ Add Complete"); User u=userdao.read (user); System.out.println ("============ Get:" +u.getname ()); }

Oh, the basic integration is done.

Jedis and spring integration and simple use of redistemplate operations

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.