In-depth understanding of the use of Spring Redis (i), Spring Redis basic usage

Source: Internet
Author: User
Tags redis server

There are many examples of the use of the Spring Redis Framework on the web. But in the recent period of their own use, found that these tutorials are introductory tutorials, including a lot of ways to use, and the spring Redis Rich API is very different, is a waste of such a good framework. Here, we understand the use of spring redis in comparison to the previous use of Hibernate in spring ORM. (This article does not explain the use of basic Redis commands)

1. Redis Usage Scenarios

Redis is an open source API that is written in ANSI C, supports the web, can be persisted in memory, key-value databases, and provides multiple languages.

As we all know, database bottlenecks are most likely to occur in everyday applications. The data volume is too large and frequent queries, due to the limitations of disk IO performance , resulting in lower performance of the project.

This time, the memory-based caching framework can solve many of our problems. such as Memcache,redis and so on. Putting some frequently used data into cache reads greatly reduces the burden on the database. Improves the performance of the system.

In fact, for Hibernate's Level two cache, this is the same truth. Solve the bottleneck of the hard disk by using the high-speed reading and writing speed of memory.

2. Configure the use of Redis

First, we need to introduce a basic jar package. The basic references in Maven are as follows:

<Dependency>            <groupId>Org.springframework.data</groupId>            <Artifactid>Spring-data-redis</Artifactid>            <version>1.4.2.RELEASE</version>        </Dependency>        <Dependency>            <groupId>Redis.clients</groupId>            <Artifactid>Jedis</Artifactid>            <version>2.6.2</version>        </Dependency>   

Then, configure the following in ApplicationContext:

<BeanID= "Poolconfig"class= "Redis.clients.jedis.JedisPoolConfig">        < Propertyname= "Maxidle"value= "${redis.maxidle}" />        < Propertyname= "Maxtotal"value= "${redis.maxactive}" />        < Propertyname= "Maxwaitmillis"value= "${redis.maxwait}" />        < Propertyname= "Testonborrow"value= "${redis.testonborrow}" />    </Bean>    <BeanID= "ConnectionFactory"class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory"P:host-name= "${redis.host}"P:port= "${redis.port}"P:password= "${redis.pass}"P:pool-config-ref= "Poolconfig" />    <BeanID= "Stringserializer"class= "Org.springframework.data.redis.serializer.StringRedisSerializer"/>    <!--open transactions, which can be controlled by transcational annotations -    <BeanID= "Redistemplate"class= "Org.springframework.data.redis.core.RedisTemplate">        < Propertyname= "ConnectionFactory"ref= "ConnectionFactory" />        < Propertyname= "Keyserializer"ref= "Stringserializer" />        < Propertyname= "Enabletransactionsupport"value= "true" />    </Bean>

For hibernate configuration, the first poolconfig is the configuration of the connection pool. Including the maximum number of connections, number of queues, survival time, maximum wait time and so on, there are some additional configuration, please directly click on the Jedispoolconfig class source code, to view.

If you do not understand the meaning of these configurations, be sure to take the thread pool and learn it.

The first configuration is the connection factory, as the name implies, the most basic use must be to open and close the connection. We need to configure the Redis server's account password, port number. (You can also configure index for the database, but I use the default database of Redis, which is the No. 0 one)

The last configuration is particularly important. This is similar to the hibernatedaosupport provided by spring.

Next, all the explanations will be unfolded around this class.

3. Use of Redistemplate

This class, as a template class, provides a lot of quick-to-use Redis APIs without needing to maintain connections and transactions on their own.

At first, the Baseredisdao I created was inherited from this class. The advantage of inheritance is that each of my DAO, can freely control the serializer, the freedom to control whether you need transactions, this first need not understand, followed my current configuration method to be able to.

The template provides a range of operation, such as Valueoperation,hashoperation,listoperation,setoperation, to manipulate Redis for different data types.

The redistemplate also provides the corresponding *operationseditor, which is used to inject the corresponding operation directly through Redistemplate. We're not talking about this for the moment.

For the following Test1 method, we do not need to consider, first understand through redistemplate to use connection operation Redis.

The test code is as follows:

 PackageCn.test.spjedis;ImportJavax.annotation.Resource;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.dao.DataAccessException;Importorg.springframework.data.redis.connection.RedisConnection;ImportOrg.springframework.data.redis.core.RedisCallback;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.data.redis.core.ValueOperations;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportCom.cn.redis2.dao.IncrDao; the @RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= "Classpath:applicationContext.xml") Public classTestredis {@Resource (name= "Redistemplate")    Privateredistemplate<string, string> template;//inject the template as Listoperations//As for why this can be injected. Need reference abstractbeanfactory Dogetbean//Super.setvalue (((redisoperations) value). Opsforvalue ()); This line of code relies on an editor@Resource (name = "Redistemplate")    PrivateValueoperations<string, object>Vops;  Public voidTestset () {Template.execute (NewRediscallback<boolean>() {@Override PublicBoolean Doinredis (redisconnection connection)throwsDataAccessException {byte[] key = "Tempkey". GetBytes (); byte[] value = "Tempvalue". GetBytes ();                Connection.set (key, value); return true;    }        }); }         Public voidTestSet1 () {Vops.set ("Tempkey", "Tempvalue"); } @AutowiredPrivateIncrdao incr; @Test Public voidAddlink () {System.out.println (INCR.INCR (13)); System.out.println (Incr.get (13)); }    }

This is the two tests that are inserted into a string type. The test method uses the template class commit callback (Rediscallback) method to manipulate the data using Jedis connection. Is there any déjà vu in this part?

Hibernatetemplate's Hibernatecallback, and the DoWork and Doreturningwork methods in the Hibernate session class, are all using this mechanism, Convenient for the unified management of the connection or session.

 Public intExcutehqlupdate (FinalString HQL,FinalObject ... params) {        returnGethibernatetemplate (). Executewithnativesession (NewHibernatecallback<integer>() {@Override @SuppressWarnings ("Unchecked")             PublicInteger Doinhibernate (Session session)throwshibernateexception {Query queryobject=session.createquery (HQL); if(Params! =NULL) {                     for(inti = 0; i < params.length; i++) {Queryobject.setparameter (I, params[i]); }                }                returnqueryobject.executeupdate ();    }        }); }

4. Summary

In this section, we talk about the use of Spring Redis configuration, the basic features, and the introduction of using Redistemplate. Through the comparison of the previous hibernatetemplate, we should also have a certain understanding of the basic design of redistemplate. In the next section, we will conduct in-depth learning redistempalte.

In-depth understanding of the use of Spring Redis (i), Spring Redis basic usage

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.