Spring MVC Spring Data Redis redistemplate [Go]

Source: Internet
Author: User

First, Concept introduction:

Redis:

Redis is an open source Key-value database, run in memory, written by ANSI C, detailed information on the Redis official website above, because I myself through Google and other channels to learn Redis, took a lot of detours, So summarize a learning path I think is good for everyone:

1. The Little Redis Book

is an open source PDF, only 29 pages of English documents, after reading the basic concept of redis should be almost familiar with, the rest can go to the Redis official website familiar with the relevant commands.

2. "Redis Design and implementation"

If you want to go further, recommend this book, now out to the second edition, there are paper books can be purchased. The above describes some of the Redis design concepts, and gives some of the internal implementation, and the data structure of the C language definition, there are some basic C language basis, you can see clearly.

3.Redis 2.6 Source Code:

The author of Redis design and implementation publishes an open source project on GitHub with detailed comments from the author.

Https://github.com/huangz1990/annotated_redis_source

Jedis:

Jedis is a Java-oriented client for Redis, which provides many interfaces for Java language calls. Can be downloaded on the Redis official website, of course, there are some open source enthusiasts to provide clients, such as Jredis, SRP, etc., recommend the use of Jedis.

Spring Data Redis

The SDR is spring's official launch, which is a sub-framework of the Spring Framework integrated Redis operation that encapsulates many of the Redis commands and makes it easy to use spring to manipulate the Redis database, and spring provides similar integrations for many tools, such as spring Data mongdb ...

What is the difference between the three? It is easy to understand that Redis is a memory-based Key-value database written in ANSI C, and Jedis is the official Redis-oriented client for Java, which provides many interfaces and methods to enable Java operations to use Redis, and spring Data Redis is a Jedis package that integrates Jedis's commands and methods to integrate with spring. As you can see in the subsequent configuration file (Redis-context.xml), spring is initialized with the Jedis class to initialize the ConnectionFactory.

Two, Spring Data Redis Demo

Project directory:

Pom.xml configuration: 

Spring jar because more, do not post out, the reader can download the following project Source view detailed configuration, in fact, pom.xml can be streamlined, not necessarily need to write so thin, I wrote so, is to see more clearly.

 1 <!--config JUnit jar--2 <dependency> 3 <groupId>junit</groupId> 4 <artifactId>junit</artifactId> 5 <version>4.8.2</version> 6 <sco          Pe>test</scope> 7 </dependency> 8 <!--config Redis data and client Jar--9 <dependency>10 <groupid>org.springframework.data</groupid>11 <artifa Ctid>spring-data-redis</artifactid>12 <version>1.0.2.release</version>13 &LT;/DEP endency>14 <dependency>15 <groupid>redis.clients</groupid>16 <arti         factid>jedis</artifactid>17 <version>2.1.0</version>18 </dependency>19 20 <!--config need jar-->21 <dependency>22 &LT;GROUPID&GT;COMMONS-LANG&LT;/GROUPID&G T;23 <artIfactid>commons-lang</artifactid>24 <version>2.6</version>25 </dependency>2 6 <dependency>27 <groupid>org.apache.geronimo.specs</groupid>28 <arti factid>geronimo-servlet_3.0_spec</artifactid>29 <version>1.0</version>30 &LT;/DEP endency>31 <!--cofig Spring jar-->32 <dependency>33 <groupid>org.springfram Ework</groupid>34 <artifactid>spring-core</artifactid>35 &LT;VERSION&GT;${ORG.SP Ringframework.version}</version>36 </dependency>37 ...

redis.properties configuration (web-inf/property/redis.properties)

The contents of the properties file will tell you what this file is for, mainly the Redis connection pool basic configuration, detailed configuration can view the Redis document.

redis.host=127.0.0.1redis.port=6379redis.pass=  redis.maxidle=300redis.maxactive=600redis.maxwait= 1000redis.testonborrow=true

Spring-context.xml (Web-inf/config/spring-context.xml)

Spring configuration, this is nothing to say, is the basic configuration of SPRINGMVC, turn on the annotation scanning function and scan path.

1 <!--activate @controller mode-2     <mvc:annotation-driven/> 3      4     <context:annotation-config/ >   5      6     <!--scan all classes in the package to complete the function of bean creation and automatic dependency injection--7     <context:component-scan base-package= "COM.CHR"/> 8  9     <!--Introducing Redis Properties Profile-->11     <import resource= "Redis-context.xml"/>

Redis-context.xml (Web/config/redis-context.xml)

Spring configures Redis, these configurations are relatively basic, look at the document is good, but there is a more important point, is the Redistemplate serializer configuration, in the back through the SDR (Spring Data Redis) and some of the ways to operate Redis.

 1 <!--scanner Redis Properties--2 <context:property-placeholder location= "Classpath:property/redis.prope Rties "/> 3 <!-Note that the jedispoolconfig is injected here, stating that the SDR also relies on Jedis--4 <bean id=" Poolconfig "class=" Redis.clients.jed Is. Jedispoolconfig "> 5 <property name=" Maxidle "value=" ${redis.maxidle} "/> 6 <property name=" Max Active "value=" ${redis.maxactive} "/> 7 <property name=" maxwait "value=" ${redis.maxwait} "/> 8 &l T;property name= "Testonborrow" value= "${redis.testonborrow}"/> 9 </bean>10 one <bean id= "ConnectionFac Tory "class=" Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "P:host-name=" ${re Dis.host} "p:port=" ${redis.port} "p:password=" ${redis.pass} "p:pool-config-ref=" Poolconfig "/>15-<b Ean id= "redistemplate" class= "org.springframework.data.redis.core.StringRedisTemplate" >17 <property name= "Co Nnectionfactory "ref="ConnectionFactory"/>18 <!--If you do not configure serializer, then the intelligent use of String when stored, if stored with the user type, it will prompt the error user can ' t cast to String !!! --<property name= "Keyserializer" >20 <bean21 class= "Org.springframewor K.data.redis.serializer.stringredisserializer "/>22 </property>23 <property name=" ValueSeriali Zer ">24 <bean25 class=" org.springframework.data.redis.serializer.JdkSerializationRedisSe Rializer "/>26 </property>27 </bean>28 <bean id=" Viewresolver " "Org.springframework.web.servlet.view.InternalResourceViewResolver"/>

Xml

Only Spring-context.xml is configured in Web. XML, because I added a statement in Spring-context.xml: <import resource="Redis-context.xml" />, so it looks like there are two configurations, in fact only need to configure Spring-context.xml. The advantages of this are: the level of the project is relatively clear, convenient for later changes.

 1 <listener> 2 <listener-class>org.springframework.web.context.contextloaderlistener</listener -class> 3 </listener> 4 5 <context-param> 6 &LT;PARAM-NAME&GT;CONTEXTCONFIGLOCATION&LT;/PA Ram-name> 7 <param-value>/WEB-INF/config/spring-context.xml</param-value> 8 </context-param& Gt 9 <servlet>11 <servlet-name>springmvc</servlet-name>12 <servlet-class>org. Springframework.web.servlet.dispatcherservlet</servlet-class>13 <init-param>14 <pa Ram-name>contextconfiglocation</param-name>15 <param-value>/web-inf/config/spring-context. Xml</param-value>16 </init-param>17 <load-on-startup>2</load-on-startup>18 &         lt;/servlet>19 <servlet-mapping>21 <servlet-name>springmvc</servlet-name>22 <url-pattern>/</url-pattern>23 </servlet-mapping> 

The following is the Java implementation of Spring MVC:

User.java(entity class, Com.chr.domain.User.java)

Note that the user class must implement the Serializable interface, which is explained later. The user class has a total of three fields defined: ID, name, password. The corresponding Setter/getter method is omitted.

1 public class User implements Serializable {2     private static final long serialversionuid = 522889572773714584L; 3
   4     private string ID; 5     private string name; 6     private string password; 7      8 public     User () {} 9     1 0 public     User (String id,string name,string password) {One         this.id = id;12         this.name = name;13         This.password = password;14     }

Useroperationsservice.java(Service interface, Com.chr.service.UserOperationsService.java)

There are two methods defined in the service interface:

The Add method is used to add a user instance to Redis, and GetUser removes the user instance from Redis.

1 public interface Useroperationsservice {2     void Add (user user); 3     user getUser (String key); 4     5}

Useroperationsserviceimpl.java(Service implementation class, implement service pretext Com.chr.service.impl. Useroperationsserviceimpl.java)

 1 @Service 2 public class Useroperationsserviceimpl implements Useroperationsservice {3 @Autowired 4 private Red Istemplate redistemplate;          5 6 @Override 7 public void Add (user user) {8//TODO auto-generated method stub 9/*10 * Boolean result = Redistemplate.execute (new rediscallback<boolean> () {One * public boolean Doinredis (Redis          Connection redisconnection) throws12 * DataAccessException {redisserializer<string> Redisserializer =13 * redistemplate. Getstringserializer (); Byte[] Key =14 * Redisserializer.serialize (User.getid ()); Byte[] Value =15 * redisserializer.serialize (User.getname ()); Return16 * REDISCONNECTION.SETNX (key, value); } }); Return result;17 */18 valueoperations<string, user> valueops = redisTemplate19. Ops Forvalue (), Valueops.set (User.getid (), user),}22 @Override25 Public user GetUser (String Key) {valueoperations<string, user> valueops = RedisTemplate27. Opsforvalue (); 28 User user = Valueops.get (key), return user;30}31 32}

Redistemplate and Serializer Detailed

You can see that I commented out a piece of code in the code, and now I can explain the two questions left behind. The first is the configuration of the redistemplate in Redis.xml, while configuring two Serializer:keyserializer implements the Stringredisserializer,valueserializer implementation Jdkserializat Ionredisserializer.

First, why to use serializer

Because Redis is key-value data in memory, key is simple string,key does not seem to have a length limit, but in principle should be as short and readable as possible, regardless of whether it is based on persistent storage, key is in memory throughout the service life cycle, Therefore, reducing the size of key can effectively save memory, but also can optimize the efficiency of key retrieval.

Value in Redis, the storage plane is still based on string, at the logical level, which can be string/set/list/map, but Redis uses different "encoding" data structure types to represent them for performance reasons. (Example: linkedlist,ziplist, etc.).

So it can be understood that, in fact, Redis in the storage of data, all the data into the form of byte[] array, then when accessing the data, the data format needs to be converted, then the use of serialization and deserialization, which is why the need to configure serializer reasons.

Second, the SDR supported serialization strategy:

(Detailed API documentation)

    • Jdkserializationredisserializer:
    • Stringredisserializer:
    • Jacksonjsonredisserializer:
    • Oxmserializer:

Among them, Jdkserializationredisserializer and Stringredisserializer are the most basic serialization strategies, where "Jacksonjsonredisserializer" and " Oxmserializer "are all based on stirng storage, so they are more" advanced "serialization (eventually using string parsing and building Java objects).

The basic recommendation is to use Jdkserializationredisserializer and Stringredisserializer, because the other two serialization policies are cumbersome to use, and if you really need to serialize them into JSON and XML formats, You can use Java code to convert a string into the appropriate JSON and XML.

Third, the use of serializer

In this project, the corresponding Serializer,key is configured directly in the configuration file using the Stringredisserializer,value is Jdkserializationredisserializer, because in this project, Key is UserID, String type, value is User Java class, that is Pojo, so use Jdkserializationredisserializer.

It is certainly convenient to configure serializer directly in the redistemplate, since it is not necessary to configure serializer again when you want to access data in Redis, but this is limited to only one data type, such as only <string in this project Userid,user user> types of data need to be stored, if there are multiple data types, configuration files in the configuration is not convenient, then we can access the data, that is, the service implementation class access data operation when the corresponding serializer specified.

So there are two options for programming:

1. Configure the serializer in Redistemplate (this is the way this project is used)

valueoperations<string, user> valueops = Redistemplate                . Opsforvalue (); Valueops.set (User.getId (), User);

2. Do not configure serializer in Redistemplate, but specify serializer separately in the service's implementation class. Just like the code for the Useroperationsserviceimpl.java comment:

1 Boolean result = Redistemplate.execute (new rediscallback<boolean> () {2 Public      Boolean Doinredis ( Redisconnection redisconnection) throws DataAccessException {3          redisserializer<string> RedisSerializer = Redistemplate. Getstringserializer (); 4          byte[] key = Redisserializer.serialize (User.getid ()); 5          byte[] value = Redisserializer.serialize ( User.getname ()); 6          return Redisconnection.setnx (key, value);}); 7     return Result;8}

Iv. redistemplate

Description of Redistemplate in the official SDR document: The template is in fact the central class of the Redis module due to its rich feature set. The template offers a high-level abstraction for Redis interactions.

The redistemplate can call Valueoperations and listoperations, and so on, respectively, the advanced encapsulation of REDIS commands.

But Valueoperations and so on, these commands are eventually transformed into Rediscallback to execute. That is, by using rediscallback, you can achieve stronger functionality, the SDR document describes Rediscallback: Redistemplate and Stringredistemplate allow the developer to Talk directly to Redis through the Rediscallback interface. This gives all control to the developer as it talks directly to the redisconnection.

You can refer to the API documentation for the specific use method.

Usercontroller.java(Controller class, Com.chr.controller)

1 @Controller 2 @RequestMapping (value = "/redis") 3 public class Usercontroller {4     @Autowired 5     Private Useropera Tionsserviceimpl Useroperationsservice; 6     Private User user; 7  8     @RequestMapping (value = "/adduser", method = Requestmethod.post) 9     Public String AddUser (             value = "Id", Required = True) string id,11             @RequestParam (value = "Name", require D = True) string name,12             @RequestParam (value = "password", required = True) string password) {         user = new User (I d, name, password);         useroperationsservice.add (user);         "/web-inf/jsp/addusersuccess.jsp"; 16     }17     @RequestMapping (value = "/adduser", method = Requestmethod.get), public     String AddUser () {20< C15/>return "/web-inf/jsp/adduser.jsp";     }22}

Only part of the code is posted here (adduser code), the rest of the GetUser code is similar, you can download the source view.

There are two methods, the Get and Post,get methods return directly to the form Fill page, which enables post to adduser add user.

adduser.jsp

<form id= "AddUser" name= "AddUser" action= "Redis/adduser" method= "POST" >                id:<input id= "id" name= "id" type = "text"/><br/>                name:<input id= "name" name= "name" type= "text"/><br/>                 password:< Input id= "password" name= "password" type= "password"/><br/>                <input value= "Add"                    type= "Submit"/ ></form>

III. Deployment Run

Finally deployed to Tomcat, the browser runs: Http://localhost:8080/redis-web/redis/addUser

Fill in the Information and click Add button to jump to the results page

The whole project is just a demo of the basic use of spring integrated Redis, because I have limited knowledge, such as errors or biases in the text, please put forward. Thank you very much:)

Iv. Project Source code:

Http://files.cnblogs.com/edwinchen/redis-web.rar

Spring MVC Spring Data Redis redistemplate [Go]

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.