Sample code for Redis integration with Spring (spring ES3en ES4en)

  • 2020-10-23 20:06:57
  • OfStack

Spring-data-redis is one part of the spring family. It provides access to redis services through simple configuration in srping applications, highly encapsulates the reids underlying development package (Jedis, JRedis, and RJC), provides redis various operations, exception handling and serialization, supports publish and subscribe, and implements spring 3.1 cache.

Liverpoolfc.tv: http: / / projects. spring. io/spring - data - redis /

Address of the project: https: / / github com/spring - projects/spring data -- redis

1. Function introduction of ES40en-ES41en-redis

The jedis client has the following deficiencies in programming implementation:

1)connection management lacks automation, and the design of connection-pool lacks necessary container support.

2) Data manipulation needs to be concerned with "serialization"/" deserialization ", because jedis's client API accepts data types string and byte, and needs additional support for structured data (json,xml,pojo, etc.) operations.

3) Transaction operations are hardcoded purely.

4)pub/sub features, lack of necessary design mode support, and need to pay too much attention to developers.

spring-data-redis provides the following functions for jedis:

1. Automatic connection pool management, providing a highly encapsulated "RedisTemplate" class

2. Categorize and encapsulate a large number of api in jedis client, encapsulate the same type of operation as operation interface

ValueOperations: Simple ES90en-V operation SetOperations: set type data manipulation ZSetOperations: zset type data manipulation HashOperations: Data manipulation for type map ListOperations: Data manipulation for type list

3. bound (binding) for key is provided. API can encapsulate the specified key through bound, and then perform a series of operations without "explicitly" specifying Key again:

BoundValueOperations BoundSetOperations BoundListOperations BoundSetOperations BoundHashOperations

4. Encapsulate transaction operations and have container control.

5. Multiple alternative strategies are provided for "serialization/deserialization" of data (RedisSerializer)

JdkSerializationRedisSerializer: Access scenario of POJO objects, using JDK's own serialization mechanism, the pojo class is serialized through ObjectInputStream/ObjectOutputStream, and finally ES128en-ES129en will store the byte sequence. Is the most commonly used serialization strategy today.
StringRedisSerializer: Key or value is a string scenario, encoded as string according to the byte sequence of data specified by charset, which is a direct encapsulation of "new String(bytes, charset)" and "string.getBytes (charset)". Is the lightest and most efficient strategy.

JacksonJsonRedisSerializer: The ES147en-ES148en tool provides the ability to convert between javabean and json, serializing pojo instances to json for storage in redis, or converting json data to pojo instances. Because the jackson tool needs to explicitly specify the Class type when serializing and deserializing, this policy is a little more complicated to wrap up. [Es158EN-mapper-ES160en tool support required]

OxmSerializer: Provides the ability to switch between javabean and xml. Currently available 3-party support includes jaxb, ES168en-ES169en; The data stored by redis will be the xml tool. With this strategy, however, programming can be difficult and inefficient; Not recommended. [Support for spring-oxm module required]
Against the "serialization and serialization" JdkSerializationRedisSerializer and StringRedisSerializer is the most basic strategy, in principle, we can store the data in any format so that the application access and parse (including applications include app, other tools such as hadoop), but still is not recommended in the design of direct use "JacksonJsonRedisSerializer" and "OxmSerializer", because both json xml, they are still String itself. If your data needs to be parsed by a third party tool, use StringRedisSerializer instead of JdkSerializationRedisSerializer. If your data format must be json or xml, then at the programming level, still use StringRedisSerializer in the redisTemplate configuration and convert to json or xml using the "SerializationUtils" tool before storage or after reading. See example below.

6. Based on the design pattern and JMS development idea, the API design of pub/sub is encapsulated to make the development more convenient.

7. spring-data-redis does not provide a good encapsulation of sharding. If your architecture is based on sharding, you need to implement it yourself, which is the only feature that sdr lacks compared to jedis.

2. serializer strategy

spring-data-redis offers a variety of serializer strategies, which are very convenient for developers using jedis. sdr offers four built-in serializer:
JdkSerializationRedisSerializer: Using JDK's serialization method (serializable interface, ObjectInputStrean, ObjectOutputStream), data is stored as a byte stream

StringRedisSerializer: String encoding, data stored as string

JacksonJsonRedisSerializer: json format for storage

OxmSerializer: xml format for storage

JdkSerializationRedisSerializer and StringRedisSerializer are the most basic serialization strategies, where "JacksonJsonRedisSerializer" and "OxmSerializer" are both based on stirng storage, so they are more "advanced" serialization (ultimately parsing and building java objects using string again).
4 types of serializer need to be declared in RedisTemplate, default is "JdkSerializationRedisSerializer" :

1) keySerializer: The serialization strategy adopted by key for ordinary ES263en-ES264en operation

2) valueSerializer: The serialization strategy adopted by value

3) hashKeySerializer: In THE hash data structure, the serialization strategy of hash-ES277en

4) hashValueSerializer: The serialization strategy of hash-ES283en

In any case, key/hashKey is recommended to use StringRedisSerializer.

3. Use examples

1. Add jar dependencies


<dependency> 
      <groupId>redis.clients</groupId> 
      <artifactId>jedis</artifactId> 
      <version>2.3.1</version> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework.data</groupId> 
      <artifactId>spring-data-redis</artifactId> 
      <version>1.5.0.RELEASE</version> 
    </dependency> 
    <dependency> 
      <groupId>org.slf4j</groupId> 
      <artifactId>slf4j-log4j12</artifactId> 
      <version>1.7.10</version> 
    </dependency> 

2. spring configuration


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:p="http://www.springframework.org/schema/p" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
 
  <context:component-scan base-package="cn.slimsmart.redis.spring" 
    annotation-config="true" /> 
 
  <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
    <property name="maxTotal" value="10"></property> 
    <property name="maxIdle" value="10"></property> 
    <property name="minIdle" value="2"></property> 
    <property name="maxWaitMillis" value="15000"></property> 
    <property name="minEvictableIdleTimeMillis" value="300000"></property> 
    <property name="numTestsPerEvictionRun" value="3"></property> 
    <property name="timeBetweenEvictionRunsMillis" value="60000"></property> 
    <property name="testOnBorrow" value="true"></property> 
    <property name="testOnReturn" value="true"></property> 
    <property name="testWhileIdle" value="true"></property> 
  </bean> 
 
  <bean id="jedisConnectionFactory" 
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 
    destroy-method="destroy"> 
    <property name="hostName" value="192.168.100.205" /> 
    <property name="port" value="6379" /> 
    <property name="timeout" value="15000" /> 
    <property name="database" value="0" /> 
    <property name="password" value="" /> 
    <property name="usePool" value="true" /> 
    <property name="poolConfig" ref="jedisPoolConfig" /> 
  </bean> 
 
  <!-- redis template definition p Said to the bean Properties are injected in the format of p: The property name = Injected object   The effect and in bean Use inside <property> The label 1 sample  --> 
  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" 
    p:connection-factory-ref="jedisConnectionFactory"> 
    <!--  Serialization mode   advice key/hashKey using StringRedisSerializer .  --> 
    <property name="keySerializer"> 
      <bean 
        class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
    </property> 
    <property name="hashKeySerializer"> 
      <bean 
        class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
    </property> 
    <property name="valueSerializer"> 
      <bean 
        class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 
    </property> 
    <property name="hashValueSerializer"> 
      <bean 
        class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 
    </property> 
 
  </bean> 
  <!--  right string Encapsulation of operations  --> 
  <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" 
    p:connection-factory-ref="jedisConnectionFactory" /> 
<!--     <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate"/> --> 
     
</beans> 

3. java code

Entity class:


package cn.slimsmart.redis.spring.data.redis.demo; 
 
import java.io.Serializable; 
import java.util.Date; 
 
public class Order implements Serializable{ 
  private static final long serialVersionUID = 1L; 
   
  private String id; 
  private String orderNo; 
  private double price; 
  private Date createDate; 
   
  public Order(String id,String orderNo,double price,Date createDate){ 
    this.id = id; 
    this.orderNo = orderNo; 
    this.price = price; 
    this.createDate = createDate; 
  } 
   
  public Order(){ 
     
  } 
  public String getId() { 
    return id; 
  } 
  public void setId(String id) { 
    this.id = id; 
  } 
  public String getOrderNo() { 
    return orderNo; 
  } 
  public void setOrderNo(String orderNo) { 
    this.orderNo = orderNo; 
  } 
  public double getPrice() { 
    return price; 
  } 
  public void setPrice(double price) { 
    this.price = price; 
  } 
  public Date getCreateDate() { 
    return createDate; 
  } 
  public void setCreateDate(Date createDate) { 
    this.createDate = createDate; 
  } 
} 

redis action class


package cn.slimsmart.redis.spring.data.redis.demo; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.redis.core.RedisOperations; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.data.redis.core.ValueOperations; 
import org.springframework.stereotype.Repository; 
 
@Repository 
public class OrderDao { 
 
  @Autowired 
  private RedisTemplate<String,Order> redisTemplate; 
 
  public void save(Order order) { 
    /*redisTemplate.opsForList(); 
    redisTemplate.opsForSet(); 
    redisTemplate.opsForHash()*/ 
    ValueOperations<String, Order> valueOper = redisTemplate.opsForValue(); 
    valueOper.set(order.getId(), order); 
  } 
 
  public Order read(String id) { 
    ValueOperations<String, Order> valueOper = redisTemplate.opsForValue(); 
    return valueOper.get(id); 
  } 
 
  public void delete(String id) { 
    ValueOperations<String, Order> valueOper = redisTemplate.opsForValue(); 
    RedisOperations<String,Order> RedisOperations = valueOper.getOperations(); 
    RedisOperations.delete(id); 
  } 
} 

Reference code: spring-ES317en-ES318en-ES319en_ES320en51.rar


Related articles: