In-depth understanding of the use of Spring Redis (I), basic use of Spring Redis, springredis

Source: Internet
Author: User

In-depth understanding of the use of Spring Redis (I), basic use of Spring Redis, springredis

There are many examples on the Internet about the use of spring redis framework. However, during my recent usage, I found that these tutorials are all introductory tutorials, including many usage methods, which are quite different from the rich APIs of spring redis. This is a waste of such an excellent framework. Here, we will compare the previous use of hibernate in spring orm to understand the use of spring redis. (This article does not explain how to use basic redis commands)

1. Redis application scenarios

Redis is an open-source log-type and Key-Value database written in ansi c language that supports Network, memory-based persistence, and provides APIs in multiple languages.

We all know that database bottlenecks are the most common in daily applications. The data volume is too large and frequently queried. Due to the limitation of disk I/O performance, the project performance is getting lower and lower.

At this time, the memory-based Cache framework can solve many of our problems. Such as Memcache and Redis. Putting frequently-used data into the cache for reading, greatly reducing the burden on the database. This improves the system performance.

In fact, the second-level cache of hibernate is the same. Use the high-speed memory read/write speed to solve the hard disk bottleneck.

 

2. Configure redis

First, we need to introduce the 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:

<Bean id = "poolConfig" class = "redis. clients. jedis. jedisPoolConfig "> <property name =" maxIdle "value =" $ {redis. maxIdle} "/> <property name =" maxTotal "value =" $ {redis. maxActive} "/> <property name =" maxWaitMillis "value =" $ {redis. maxWait} "/> <property name =" testOnBorrow "value =" $ {redis. testOnBorrow} "/> </bean> <bean id =" connectionFactory "class =" org. springframework. data. redis. connection. jedis. jedisConnec TionFactory "p: host-name =" $ {redis. host} "p: port =" $ {redis. port} "p: password =" $ {redis. pass} "p: pool-config-ref =" poolConfig "/> <bean id =" stringSerializer "class =" org. springframework. data. redis. serializer. stringRedisSerializer "/> <! -- Enable transactions. You can use transcational annotations to control transactions. --> <bean id = "redisTemplate" class = "org. springframework. data. redis. core. redisTemplate "> <property name =" connectionFactory "ref =" connectionFactory "/> <property name =" keySerializer "ref =" stringSerializer "/> <property name =" enableTransactionSupport "value = "true"/> </bean>

 

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

If you do not understand the meaning of these configurations, you must study the thread pool well.

 

The first configuration is the connection factory. As the name suggests, the most basic use must be to open and close the connection. We need to configure the account password and port number of the redis server for it. (The index of the database can be configured here, but I have been using the default redis database, that is, 0th)

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

Next, all the explanations will be centered on this class.

 

3. Use of RedisTemplate

As a template class, this class provides a lot of APIS for using redis quickly, without the need to maintain connections and transactions on your own.

Initially, the BaseRedisDao I created inherits from this class. The benefit of inheritance is that each of my Dao can control the serializer freely and control whether transactions are required, follow my current configuration method.

 

Template provides a series of operation functions, such as valueOperation, HashOperation, ListOperation, and SetOperation, to operate Redis of different data types.

In addition, RedisTemplate also provides * OperationsEditor for direct injection of corresponding Operation through RedisTemplate. We will not talk about this for the time being.

 

For the following test1 method, we do not need to consider it for the moment. First, we need to know how to use the RedisTemplate to operate Redis using connection.

The Test code is as follows:

Package cn. test. spjedis; import javax. annotation. resource; import org. junit. test; import org. junit. runner. runWith; import org. springframework. beans. factory. annotation. autowired; import org. springframework. dao. dataAccessException; import org. springframework. data. redis. connection. redisConnection; import org. springframework. data. redis. core. redisCallback; import org. springframework. data. redis. core. redisTemplat E; import org. springframework. data. redis. core. valueOperations; import org. springframework. test. context. contextConfiguration; import org. springframework. test. context. junit4.SpringJUnit4ClassRunner; import com.cn. redis2.dao. incrDao; @ RunWith (SpringJUnit4ClassRunner. class) @ ContextConfiguration (locations = "classpath: applicationContext. xml ") public class TestRedis {@ Resource (name =" redisTemplate ") private RedisTemplate <String, String> template; // inject the template as ListOperations // Why can this be injected. Please refer to AbstractBeanFactory doGetBean // super. setValue (RedisOperations) value ). opsForValue (); this line of code relies on an editor @ Resource (name = "redisTemplate") private ValueOperations <String, Object> vOps; public void testSet () {template.exe cute (new RedisCallback <Boolean> () {@ Override public Boolean doInRedis (RedisConnection connection) throws DataAccessException {byte [] key = "tempkey ". getBytes (); byte [] value = "tempvalue ". getBytes (); connection. set (key, value); return true ;}}) ;}public void testSet1 () {vOps. set ("tempkey", "tempvalue") ;}@ Autowired private IncrDao incr; @ Test public void addLink () {System. out. println (incr. incr (13); System. out. println (incr. get (13 ));}}

 

This is two tests for String type insertion. In the test method, the template class commit callback (RedisCallBack) method is used to operate data using jedis connection. Have you ever been familiar with this part?

 

HibernateTemplate's HibernateCallback and the doWork and doReturningWork methods in the Hibernate Session class all use this mechanism to facilitate unified management of connections or sessions.

public int excuteHqlUpdate(final String hql,final Object ...params){        return getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {            @Override            @SuppressWarnings("unchecked")            public Integer doInHibernate(Session session) throws HibernateException {                Query queryObject = session.createQuery(hql);                if (params != null) {                    for (int i = 0; i < params.length; i++) {                        queryObject.setParameter(i, params[i]);                    }                }                return queryObject.executeUpdate();            }        });    }

 

4. Summary

This section describes how to configure and use spring redis, basic features, and the introduction of RedisTemplate. Through the comparison of HibernateTemplate, we should also have a certain understanding of the basic design of RedisTemplate. Next, we will go deep into RedisTempalte.

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.