Redis学习笔记(6)——SpringDataRedis入门

一、SpringDataRedis简介

  Spring-data-redis是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操作
    SetOperations:set类型数据操作
    ZSetOperations:zset类型数据操作
    HashOperations:针对map类型的数据操作
    ListOperations:针对list类型的数据操作

二、SpringDataRedis入门案例

2.1 准备工作

  (1)构建Maven工程——SpringDataRedisDemo

  (2)引入Spring相关依赖、引入JUnit依赖 

  (3)引入Jedis和SpringDataRedis依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.pinyougou</groupId>
    <artifactId>SpringDataRedisDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- 集中定义依赖版本号 -->
    <properties>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </dependency>
        <!-- 缓存 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
    </dependencies>
</project>

  (4)在src/main/resources下创建properties文件夹,建立redis-config.properties

redis.host=127.0.0.1 
redis.port=6379 
redis.pass=
redis.database=0 
redis.maxIdle=300 
redis.maxWait=3000 
redis.testOnBorrow=true 

  (5)在src/main/resources下创建spring文件夹 ,创建applicationContext-redis.xml

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       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:property-placeholder location="classpath*:properties/redis-config.properties"/>

    <!--redis相关配置-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <!--suppress SpringXmlModelInspection -->
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>
</beans>

  maxIdle :最大空闲数

  maxWaitMillis:连接时的最大等待毫秒数

  testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的;

2.2 值类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestValue {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void setValue() {
        redisTemplate.boundValueOps("name").set("zhangsan");
    }

    @Test
    public void getValue() {
        String str = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(str);
    }

    @Test
    public void deleteValue() {
        redisTemplate.delete("name");
    }
}

2.3 set类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestSet {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 存入值
     */
    @Test
    public void setValue() {
        redisTemplate.boundSetOps("nameset").add("曹操");
        redisTemplate.boundSetOps("nameset").add("刘备");
        redisTemplate.boundSetOps("nameset").add("孙权");
    }

    /**
     * 提取值
     */
    @Test
    public void getValue() {
        Set members = redisTemplate.boundSetOps(("nameset")).members();
        System.out.println(members);//[孙权, 刘备, 曹操]
    }

    /**
     * 删除集合中的某一个值
     */
    @Test
    public void deleteValue() {
        redisTemplate.boundSetOps("nameset").remove("孙权");
    }

    /**
     * 删除整个集合
     */
    @Test
    public void deleteAllValue() {
        redisTemplate.delete("nameset");
    }
}

2.4 List类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestList {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 右压栈:后添加的对象排在后边
     */
    @Test
    public void testSetValue1() {
        redisTemplate.boundListOps("nameList1").rightPush("刘备");
        redisTemplate.boundListOps("nameList1").rightPush("关羽");
        redisTemplate.boundListOps("nameList1").rightPush("张飞");
    }

    /**
     * 显示右压栈集合
     */
    @Test
    public void testGetValue1() {
        List list = redisTemplate.boundListOps("nameList1").range(0, 10);
        System.out.println(list);//[刘备, 关羽, 张飞]
    }

    /**
     * 左压栈:后添加的对象排在前边
     */
    @Test
    public void testSetValue2() {
        redisTemplate.boundListOps("nameList2").leftPush("刘备");
        redisTemplate.boundListOps("nameList2").leftPush("关羽");
        redisTemplate.boundListOps("nameList2").leftPush("张飞");
    }

    /**
     * 显示左压栈集合
     */
    @Test
    public void testGetValue2() {
        List list = redisTemplate.boundListOps("nameList2").range(0, 10);
        System.out.println(list);//[张飞, 关羽, 刘备]
    }

    /**
     * 查询集合某个元素
     */
    @Test
    public void testSearchByIndex() {
        String str = (String) redisTemplate.boundListOps("nameList1").index(1);
        System.out.println(str);//关羽
    }

    /**
     * 移除集合某个元素
     */
    @Test
    public void testRemoveByIndex() {
        //1代表移除的个数
        redisTemplate.boundListOps("nameList1").remove(1, "关羽");
    }
}

2.5 Hash类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestHash {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 存入值
     */
    @Test
    public void testSetValue() {
        redisTemplate.boundHashOps("namehash").put("a", "唐僧");
        redisTemplate.boundHashOps("namehash").put("b", "悟空");
        redisTemplate.boundHashOps("namehash").put("c", "八戒");
        redisTemplate.boundHashOps("namehash").put("d", "沙僧");
    }

    /**
     * 提取所有的KEY
     */
    @Test
    public void testGetKeys() {
        Set keys = redisTemplate.boundHashOps("namehash").keys();
        System.out.println(keys);//[a, b, c, d]
    }

    /**
     * 提取所有的值
     */
    @Test
    public void testGetValues() {
        List values = redisTemplate.boundHashOps("namehash").values();
        System.out.println(values);//[唐僧, 悟空, 八戒, 沙僧]
    }

    /**
     * 根据KEY提取值
     */
    @Test
    public void testGetValueByKey() {
        Object o = redisTemplate.boundHashOps("namehash").get("b");
        System.out.println(o);//悟空
    }

    /**
     * 根据KEY移除值
     */
    @Test
    public void testRemoveValueByKey() {
        redisTemplate.boundHashOps("namehash").delete("c");
    }
}

 

posted @ 2019-03-23 21:47  yi0123  阅读(300)  评论(0编辑  收藏  举报