Spring集成redis(Spring Data Redis)

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 转载地址:http://blog.csdn.net/zhu_tianwei/article/details/44923001Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

转载地址:http://blog.csdn.net/zhu_tianwei/article/details/44923001

Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。
官网:http://projects.spring.io/spring-data-redis/
项目地址:https://github.com/spring-projects/spring-data-redis
一、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);  
    }  
}  
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
21天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
52 0
|
25天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
159 0
|
22天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
42 1
|
1月前
|
缓存 NoSQL Java
springboot中集成redis,二次封装成工具类
springboot中集成redis,二次封装成工具类
169 0
|
1月前
|
Java 数据库连接 数据库
Spring Boot整合MyBatis Plus集成多数据源轻松实现数据读写分离
Spring Boot整合MyBatis Plus集成多数据源轻松实现数据读写分离
26 2
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
45 1
|
1月前
|
存储 NoSQL Java
[Redis]——Spring整合Redis(SpringDataRedis)
[Redis]——Spring整合Redis(SpringDataRedis)
|
NoSQL Java 数据库
|
Java Spring 数据格式
spring 整合redis
用的是最新的jedis-2.6.2.jar这个包,这个和以前的有点不同。还需要添加spring-data-redis-1.2.1.RELEASE.jar和commons-pool2-2.3.jar。 在类路径下创建spring-redis-config.
923 0
|
NoSQL Java Redis
redis和spring整合
pom构建: [html] view plain copy  print? &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;   &lt;groupId&gt;com.x.redis&lt;/groupId&gt;   &lt;artifactId&gt;springredis&l
1023 0

热门文章

最新文章