当前位置: 移动技术网 > IT编程>开发语言>Java > Redis 集成Spring的示例代码(spring-data-redis)

Redis 集成Spring的示例代码(spring-data-redis)

2019年07月19日  | 移动技术网IT编程  | 我要评论

spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(jedis,  jredis, and rjc)进行了高度封装,redistemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

官网:

项目地址:

一、spring-data-redis功能介绍

jedis客户端在编程实施方面存在如下不足:

1)connection管理缺乏自动化,connection-pool的设计缺少必要的容器支持。

2)数据操作需要关注“序列化”/“反序列化”,因为jedis的客户端api接受的数据类型为string和byte,对结构化数据(json,xml,pojo等)操作需要额外的支持。

3)事务操作纯粹为硬编码。

4)pub/sub功能,缺乏必要的设计模式支持,对于开发者而言需要关注的太多。

spring-data-redis针对jedis提供了如下功能:

1.连接池自动管理,提供了一个高度封装的“redistemplate”类

2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口

  • valueoperations:简单k-v操作
  • setoperations:set类型数据操作
  • zsetoperations:zset类型数据操作
  • hashoperations:针对map类型的数据操作
  • listoperations:针对list类型的数据操作

3.提供了对key的“bound”(绑定)便捷化操作api,可以通过bound封装指定的key,然后进行一系列的操作而无须“显式”的再次指定key,即boundkeyoperations:

  • boundvalueoperations
  • boundsetoperations
  • boundlistoperations
  • boundsetoperations
  • boundhashoperations

4.将事务操作封装,有容器控制。

5.针对数据的“序列化/反序列化”,提供了多种可选择策略(redisserializer)

jdkserializationredisserializer:pojo对象的存取场景,使用jdk本身序列化机制,将pojo类通过objectinputstream/objectoutputstream进行序列化操作,最终redis-server中将存储字节序列。是目前最常用的序列化策略。
stringredisserializer:key或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是“new string(bytes, charset)”和“string.getbytes(charset)”的直接封装。是最轻量级和高效的策略。

jacksonjsonredisserializer:jackson-json工具提供了javabean与json之间的转换能力,可以将pojo实例序列化成json格式存储在redis中,也可以将json格式的数据转换成pojo实例。因为jackson工具在序列化和反序列化时,需要明确指定class类型,因此此策略封装起来稍微复杂。【需要jackson-mapper-asl工具支持】

oxmserializer:提供了将javabean与xml之间的转换能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存储的数据将是xml工具。不过使用此策略,编程将会有些难度,而且效率最低;不建议使用。【需要spring-oxm模块的支持】
针对“序列化和发序列化”中jdkserializationredisserializer和stringredisserializer是最基础的策略,原则上,我们可以将数据存储为任何格式以便应用程序存取和解析(其中应用包括app,hadoop等其他工具),不过在设计时仍然不推荐直接使用“jacksonjsonredisserializer”和“oxmserializer”,因为无论是json还是xml,他们本身仍然是string。如果你的数据需要被第三方工具解析,那么数据应该使用stringredisserializer而不是jdkserializationredisserializer。如果你的数据格式必须为json或者xml,那么在编程级别,在redistemplate配置中仍然使用stringredisserializer,在存储之前或者读取之后,使用“serializationutils”工具转换转换成json或者xml,请参见下文实例。

6.基于设计模式,和jms开发思路,将pub/sub的api设计进行了封装,使开发更加便捷。

7.spring-data-redis中,并没有对sharding提供良好的封装,如果你的架构是基于sharding,那么你需要自己去实现,这也是sdr和jedis相比,唯一缺少的特性。

二、serializer策略

spring-data-redis提供了多种serializer策略,这对使用jedis的开发者而言,实在是非常便捷。sdr提供了4种内置的serializer:
jdkserializationredisserializer:使用jdk的序列化手段(serializable接口,objectinputstrean,objectoutputstream),数据以字节流存储

stringredisserializer:字符串编码,数据以string存储

jacksonjsonredisserializer:json格式存储

oxmserializer:xml格式存储

其中jdkserializationredisserializer和stringredisserializer是最基础的序列化策略,其中“jacksonjsonredisserializer”与“oxmserializer”都是基于stirng存储,因此它们是较为“高级”的序列化(最终还是使用string解析以及构建java对象)。
redistemplate中需要声明4种serializer,默认为“jdkserializationredisserializer”:

1) keyserializer :对于普通k-v操作时,key采取的序列化策略

2) valueserializer:value采取的序列化策略

3) hashkeyserializer: 在hash数据结构中,hash-key的序列化策略

4) hashvalueserializer:hash-value的序列化策略

无论如何,建议key/hashkey采用stringredisserializer。

三、使用实例

1.添加jar依赖

<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配置

<?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表示对该bean里面的属性进行注入,格式为p:属性名=注入的对象 效果与在bean里面使用<property>标签一样 --> 
  <bean id="redistemplate" class="org.springframework.data.redis.core.redistemplate" 
    p:connection-factory-ref="jedisconnectionfactory"> 
    <!-- 序列化方式 建议key/hashkey采用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> 
  <!-- 对string操作的封装 --> 
  <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代码

实体类:

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操作类

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); 
  } 
} 

参考代码:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网