黑马程序员技术交流社区

标题: 【上海校区】SpringDataRedis的入门 [打印本页]

作者: 阿莱    时间: 2019-7-11 17:36
标题: 【上海校区】SpringDataRedis的入门
本帖最后由 阿莱 于 2019-7-11 17:38 编辑

【上海校区】SpringDataRedis的入门

前言:

Jedis是Redis官方推出的一款面向Java的客户端,但是API有些繁琐而且不太具备见名思意,SpringDataRedis对Jedis做了进一步的封装。


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接口

环境的搭建:

maven所需要的依赖

[XML] 纯文本查看 复制代码

    <!-- 集中定义依赖版本号 -->
    <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>

    <build>
        <plugins>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

        </plugins>
    </build>



Spring的配置文件:applicationContext-redis.xml

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


[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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       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/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache.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}" />
        <!--在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的-->
        <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>


连接Redis的配置文件:redis-config.properties

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


[JavaScript] 纯文本查看 复制代码
redis.host=192.168.25.128
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true


一、值类型操作

[Java] 纯文本查看 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class SpringDataRedisStrTest {

    //注入操作redis的模板

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //操作字符串,存入缓存
    @Test
    public void setStrValue(){

        redisTemplate.boundValueOps("name").set("heima-chuanzhi-it");

        System.out.println("缓存存入成功......");
    }

    //根据key从缓存中获取字符串

    @Test
    public void getStrValueByKey(){

        String name = redisTemplate.boundValueOps("name").get();

        System.out.println("name = " + name);
    }

    @Test
    public void deleStrValueByKey(){

        redisTemplate.delete("name");

        System.out.println("根据key删除成功......");
    }
}


二、set集合类型操作

[Java] 纯文本查看 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class SpringDataRedisSetTest {

    //注入操作redis的模板

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //操作set集合,存入缓冲

    @Test
    public void setSetValue(){

        redisTemplate.boundSetOps("setKey").add("刘德华");
        redisTemplate.boundSetOps("setKey").add("张学友");
        redisTemplate.boundSetOps("setKey").add("郭富城");
        redisTemplate.boundSetOps("setKey").add("黎明");

        System.out.println("操作set集合成功.....");
    }

    //根据key从缓存中或者set集合
    @Test
    public void getSetValue(){

        Set<String> set = redisTemplate.boundSetOps("setKey").members();

        for (String str : set) {

            System.out.println("str = " + str);
        }
    }

    //删除集合中的某一个值
    @Test
    public void deleteSetByValue(){

        Long num = redisTemplate.boundSetOps("setKey").remove("黎明");

        System.out.println((num==1?"删除成功":"删除失败"));
    }

    //删除整个set集合
    @Test
    public void deleteAllValue(){

        redisTemplate.delete("setKey");

        System.out.println("删除整个set集合成功......");
    }
}


三、List集合类型的操作

[Java] 纯文本查看 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class SpringDataRedisListTest {


    //注入操作redis的模板

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //右压栈:后添加的对象排在后边
    @Test
    public void setRightPressStackListValue(){

        redisTemplate.boundListOps("rList").rightPush("成龙");
        redisTemplate.boundListOps("rList").rightPush("李连杰");
        redisTemplate.boundListOps("rList").rightPush("周润发");
        redisTemplate.boundListOps("rList").rightPush("周星驰");

        System.out.println("右压栈操作List缓存成功......");
    }

    //显示右压栈集合
    @Test
    public void getRightPressStackListValue(){

        //获取rList集合的长度
        Long size = redisTemplate.boundListOps("rList").size();

        System.out.println("size = " + size);

        //获取rList集合
        List<String> rList = redisTemplate.boundListOps("rList").range(0, size);

        for (String str : rList) {

            System.out.println("str = " + str);
        }
    }


    //左压栈:后添加的对象排在前边
    @Test
    public void setLeftPressStackListValue(){

        redisTemplate.boundListOps("lList").leftPush("三国演义");
        redisTemplate.boundListOps("lList").leftPush("红楼梦");
        redisTemplate.boundListOps("lList").leftPush("水浒传");
        redisTemplate.boundListOps("lList").leftPush("西游记");


        System.out.println("左压栈操作List缓存成功......");
    }

    //显示左压栈集合
    @Test
    public void getLeftPressStackListValue(){

        //获取lList集合的长度
        Long size = redisTemplate.boundListOps("lList").size();

        System.out.println("size = " + size);

        //获取lList集合
        List<String> lList = redisTemplate.boundListOps("lList").range(0, size);

        for (String str : lList) {

            System.out.println("str = " + str);
        }
    }

    //根据索引获取某个元素
    @Test
    public void getLeftPressStackListValueByIndex(){

        String name = redisTemplate.boundListOps("lList").index(1);

        System.out.println("name = " + name);
    }

    //移除集合某个元素
    @Test
    public void removeLeftPressStackListValueByIndexAndValue(){

        Long num = redisTemplate.boundListOps("lList").remove(1, "水浒传");

        System.out.println((num==1?"删除成功":"删除失败"));
    }

}


四、Hash集合类型的操作

[Java] 纯文本查看 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class SpringDataRedisHashTest {

    //注入操作redis的模板

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //存入hash类型数据值

    @Test
    public void SetHashValue(){

        redisTemplate.boundHashOps("kHash").put("ts", "唐僧");
        redisTemplate.boundHashOps("kHash").put("wk", "悟空");
        redisTemplate.boundHashOps("kHash").put("bj", "八戒");
        redisTemplate.boundHashOps("kHash").put("ss", "沙僧");

        System.out.println("存入缓存成功......");
    }

    //获取所有的key

    @Test
    public void getHashKeys(){
        Set keys = redisTemplate.boundHashOps("kHash").keys();

        for (Object key : keys) {

            System.out.println("key = " + key);
        }
    }

    //获取所有的value
    @Test
    public void getHashValues(){
        List values = redisTemplate.boundHashOps("kHash").values();

        for (Object value : values) {

            System.out.println("value = " + value);
        }
    }

    //根据key删除hash的值

    @Test
    public void getHashValueByKey(){

        Object object = redisTemplate.boundHashOps("kHash").get("wk");

        System.out.println(object);
    }

    //根据key删除hash的值

    @Test
    public void removeHashValueByKey(){

        Object object = redisTemplate.boundHashOps("kHash").get("ss");

        System.out.println(object);
    }
}








欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2