Spring data redis Operation redis knowledge summary

  • 2020-06-23 00:20:56
  • OfStack

What is spring data - redis

spring data - redis spring - 1 part of data module, designed to support to the operation of the redis spring management projects, using java redis operation is the most commonly used is to use jedis, but not only jedis can use, like jdbc - redis jredis also belong to redis java client, between them is not compatible, if you used jedis in one project, and then later decide to abandon to switch to ES23E N-redis is more troublesome, spring-ES26en-ES27en provides the abstraction of redis's java client, which can be ignored in the development. Besides, it belongs to the first part of spring itself, which is more stable and more automatic in management than jedis alone (of course, jedis has more disadvantages than above).

spring data - redis features

1. Automatically manage connection pools, providing a highly encapsulated RedisTemplate class

2. Categorize and encapsulate a large number of api for jedis clients, encapsulate the same type of operation into Operation interface, and support the operation of 5 data types in redis.

3. Multiple alternative strategies are available for "serialization and deserialization" of data (RedisSerializer)

JdkSerializationRedisSerializer: Used when you need to store java objects.

StringRedisSerializer: Used when you need to store strings of type string.

JacksonJsonRedisSerializer: To serialize the object to json and store it in redis, it needs the support of ES63en-ES64en tool. (I haven't used it so far, so I don't know.)

Operations

redisTemplate has two methods that are often used, one is opsForXXXand the other is boundXXXOps, and XXX is the type of value. The former obtains one Opercation but does not specify key, which can operate multiple key and corresponding value within one connection (transaction). The latter gets an operation with key specified and operates only the key corresponding to this value within a connection.

ValueOperation and BoundValueOperation


ValueOperations valueOperations = redisTemplate.opsForValue();

BoundValueOperations<String, User> boundValueOps = redisTemplate.boundValueOps("key");

ValueOperation can cache Integer,String,java objects, etc. Set using the.set (key,value) method, which is used to get.

In the same way, you can get the ListOperations object, which can be used to cache List, in addition to SetOperation,HashOperation

spring-data-redis was used in spring+springmvc project

1.maven configuration, adding pom dependencies


<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-redis</artifactId>
  <version>1.3.4.RELEASE</version>
</dependency>

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.4.2</version>
</dependency>

2. spring - redis. xml configuration:


 <!--JedisPoolConfig  Connection pool parameter configuration -->
 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  <!-- Maximum number of idle instances -->
  <property name="maxIdle" value="300" />
  <!-- Maximum number of active instances -->
  <property name="maxTotal" value="600" />
  <!-- Maximum wait time when creating an instance -->
  <property name="maxWaitMillis" value="1000" />
  <!-- Validates when creating an instance -->
  <property name="testOnBorrow" value="true" />
 </bean>

 <!--JedisConnectionFactory  This is similar to configuring a database connection pool , Need to configure the JedisConnectionFactory To get through a server or connection pool redis Server connection -->
 <bean id="connectionFactory"
   class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  <property name="hostName" value="127.0.0.1"/>
  <property name="port" value="6379"/>
  <property name="usePool" value="true"/>
  <property name="poolConfig" ref="poolConfig"/>
 </bean>

 <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
 <bean id="valueSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>


 <!-- redis The template configuration  spring-data-redis provides 1 Basic generics RedisTemplate Encapsulates the underlying crud operation -->
 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  <property name="connectionFactory" ref="connectionFactory"/>
  <property name="defaultSerializer" ref="stringRedisSerializer"/>
  <property name="keySerializer" ref="stringRedisSerializer"/>
  <property name="valueSerializer" ref="valueSerializer"/>

 </bean>

Once the above configuration is complete, you are ready to use ES126en-ES127en-ES128en. To demonstrate the specific use of 1, write a simple demo.

Create the entity class User


public class User implements Serializable {

 private static final long serialVersionUID = 1L;

 /**  The user ID */
 private Long id;

 /**  The user name  */
 private String name;

 /**  The user's age  */
 private Integer age;
}

Note: If the pojo object needs to be stored in redis, then the object must implement the Serializable interface, because the pojo class stored in redis still stores string, which converts the data to the byte[] array. The data format needs to be converted at access time, which involves serialization and deserialization.

4. Create UserCcontroller


@Controller
public class UserController extends BaseController {

 @Autowired
 private IUserService userService;

 @Autowired
 private RedisTemplate<String,User> redisTemplate;

 @ResponseBody
 @RequestMapping("/redis")
 public Object redis() {

  User u1=new User();
  u1.setId(1L);
  u1.setName("wang");
  u1.setAge(22);
  redisTemplate.opsForValue().set("user:wang",u1);

  User u2=redisTemplate.opsForValue().get("user:wang");
  return u2;
 }
}

Here we store the user object in redis, read it, run the project, and test the interface to see the user object in the browser.

Common error reporting and solutions

At the beginning, I tested the function of spring-ES158en-redis, which was configured from 1 empty item, 1 dot. There were a lot of exceptions when starting.

1. Start tomcat to report an error


Caused by: java.lang.VerifyError: (class: org/springframework/data/redis/connection/jedis/JedisConnectionFactory, 
method: afterPropertiesSet signature: ()V) Incompatible argument to function

Reasons and Solutions:

In pom, the version of jedis I configured at the beginning is 2.7.3, and the version of spring-ES173en-ES174en is 1.1.1. After a search on the Internet, I found that there is a saying of ES175en-2.7.3.ES176en and ES177en-ES178en-ES179en-1.1.1.ES181en It could not be used together, so I set the version of spring-ES183en-redis to a relatively high 1.3.4 and redeployed. Sure enough, the problem was solved, and then the problem came again.

2. Start tomcat to report an error


Caused by: Java.lang.NoSuchMethodError: redis.clients.jedis.JedisShardInfo.setTimeout(I)V

Reason and solution: The same problem is caused by the version (yes, I hit them all). The version of jedis is 2.7.3, which is too high. After changing it to 2.4.3, the problem will be solved.

3. Start tomcat to report an error


java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool

Reason and solution: This GenericObjectPool USES the class in ES203en-ES204en.jar. We do not have this jar in our dependency, so we simply add dependency of ES207en-ES208en.

4. Operation interface error report


HTTP Status 500 - Request processing failed; nested exception is java.lang.ClassCastException: com.baomidou.springmvc.model.system.User cannot be cast to java.lang.String

Reason and solution: name="valueSerializer" configuration is missing in redisTemplate's property in es217EN-ES218en configuration file because value stored in redis is an user object and needs to be serialized using JdkSerializationRedisSerializer object. The solution is to configure spring-ES228en.xml above.


Related articles: