SpringDataRedis介绍

  实际项目中我们一般都会使用Redis来作为我们的缓存组件,往往又会和Spring一块使用,虽然Redis官方提供的有Jedis等客户端工具,但是使用的时候还是有些不方便,这时SpringDataRedis出现了。


Redis相关单独介绍参考:https://dpb-bobokaoya-sm.blog.csdn.net/column/info/33752


SpringDataRedis

一、什么是SpringDataRedis

  SpringDataRedis是Spring大家族中的一个成员,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。
spring-data-redis针对jedis提供了如下功能:

  1. 连接池自动管理,提供了一个高度封装的“RedisTemplate”类
  2. 针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
接口 说明
ValueOperations 简单K-V操作
HashOperations 针对map类型的数据操作
ListOperations 针对list类型的数据操作
SetOperations set类型数据操作
ZSetOperations zset类型数据操作
  1. 提供的有相关的序列化器
序列化器 说明
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模块的支持】

二、怎么使用

1.创建maven项目并添加相关依赖

  创建普通的maven项目,然后添加如下依赖

<dependencies>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>4.3.21.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.9.4version>
    dependency>
    <dependency>
        <groupId>aopalliancegroupId>
        <artifactId>aopallianceartifactId>
        <version>1.0version>
    dependency>
    <dependency>
        <groupId>org.springframework.datagroupId>
        <artifactId>spring-data-redisartifactId>
        <version>1.6.0.RELEASEversion>
    dependency>
    <dependency>
        <groupId>redis.clientsgroupId>
        <artifactId>jedisartifactId>
        <version>2.7.0version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>4.3.21.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>4.3.21.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.apache.commonsgroupId>
        <artifactId>commons-pool2artifactId>
        <version>2.3version>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.8.5version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>2.8.5version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.8.5version>
    dependency>
dependencies>

2.添加相关的配置

  添加Spring的配置文件和Redis连接信息的配置文件,如下

SpringDataRedis介绍_第1张图片

redis.properties

redis.pool.maxTotal=20
redis.pool.maxIdle=10
redis.pool.minIdle=5

redis.conn.hostName=192.168.88.120
redis.conn.port=6379

applicationContext.xml
  注意相关的序列化器的设置,设置使用的是StringRedisSerializer


<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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <context:property-placeholder
            location="classpath:redis.properties"/>
    
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.pool.maxTotal}"/>
        <property name="maxIdle" value="${redis.pool.maxIdle}"/>
        <property name="minIdle" value="${redis.pool.minIdle}"/>
    bean>
    
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.conn.hostName}"/>
        <property name="port" value="${redis.conn.port}"/>
        <property name="poolConfig" ref="poolConfig"/>
    bean>
    
    <bean id="redisTemplate"
          class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory"
                  ref="jedisConnectionFactory"/>
        
        
        
        
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        property>
        <property name="valueSerializer">
            <bean  class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        property>
    bean>
beans>

3.数据存储操作

3.1 string类型操作

/**
 * @program: spring-data-redis-demo
 * @description: Redis单元测试
 * @author: 波波烤鸭
 * @create: 2019-05-19 23:45
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 存储键值对
     */
    @Test
    public void test1(){
        this.redisTemplate.opsForValue().set("key","bobo kaoyao");
    }

    /**
     * 获取信息
     */
    @Test
    public void test2(){
        String msg = (String) this.redisTemplate.opsForValue().get("key");
        System.out.println("获取的值:"+msg);
    }

    /**
     * 测试连接
     */
    @Test
    public void test3(){
        Jedis jedis = new Jedis("192.168.88.120",6379);
        System.out.println(jedis.ping());
    }
}

SpringDataRedis介绍_第2张图片

3.2 自定义对象

/**
 * 存储自定义对象
 */
@Test
public void test4(){
    // 获取自定义对象
    Users user = new Users(1,"张三",18);
    // 更换序列化器
    this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    this.redisTemplate.opsForValue().set("users",user);
}

/**
* 获取自定义对象
*/
@Test
public void test5(){

   // 更换序列化器
   this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
   Object users = this.redisTemplate.opsForValue().get("users");
   System.out.println(users);

}

SpringDataRedis介绍_第3张图片

3.3 存储为JSON数据

/**
 * 存储自定义对象为json数据
 */
@Test
public void test6(){
    // 获取自定义对象
    Users user = new Users(1,"张三",18);
    // 更换序列化器
    this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));
    this.redisTemplate.opsForValue().set("usersjson",user);
}

/**
 * 获取自定义对象数据
 */
@Test
public void test7(){

    // 更换序列化器
    this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));
    System.out.println(this.redisTemplate.opsForValue().get("usersjson"));
}

SpringDataRedis介绍_第4张图片

3.4 List操作

  就给出了lpush命令对应的leftpush方法,其他的参考名称操作~

/**
 * @program: spring-data-redis-demo
 * @description: Redis单元测试
 * @author: 波波烤鸭
 * @create: 2019-05-19 23:45
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisList {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * List 类型
     */
    @Test
    public void test1() {
        this.redisTemplate.boundListOps("stus").leftPush("zhangsan");
        this.redisTemplate.boundListOps("stus").leftPush("lisi");
        this.redisTemplate.boundListOps("stus").leftPush("wangwu");
    }
}

SpringDataRedis介绍_第5张图片

3.5 Set操作

 /**
  * Set 类型
  */
 @Test
 public void test2() {
     redisTemplate.boundSetOps("nameset").add("bobo1");
     redisTemplate.boundSetOps("nameset").add("bobo2");
     redisTemplate.boundSetOps("nameset").add("bobo3");
 }

SpringDataRedis介绍_第6张图片

3.6 ZSet操作

 /**
  * ZSet 类型
  */
 @Test
 public void test3() {
     redisTemplate.boundZSetOps("namezset").add("xiaoming",90);
     redisTemplate.boundZSetOps("namezset").add("xiaohua",100);
     redisTemplate.boundZSetOps("namezset").add("xiaoli",70);
 }

SpringDataRedis介绍_第7张图片

3.7 Hash操作

/**
 * Hash 类型
 */
@Test
public void test4() {
    redisTemplate.boundHashOps("role").put("roleid",1001);
    redisTemplate.boundHashOps("role").put("rolename","test role");
    redisTemplate.boundHashOps("role").put("roledesc","role desc");
}

/**
 * Hash 类型 获取field对应的值
 */
@Test
public void test6() {
    Set<Object> keys = redisTemplate.boundHashOps("role").keys();
    for (Object o: keys) {
        System.out.println(o+":"+redisTemplate.boundHashOps("role").get(o));
    }
}

SpringDataRedis介绍_第8张图片

SpringDataRedis介绍_第9张图片

你可能感兴趣的:(redis专栏,#,SPRING-DATA系列)