Spring Data Redis 入门介绍

Spring Data Redis简介

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 类型数据操作
    ListOperations:针对 list 类型的数据操作
    HashOperations:针对 map 类型的数据操作
    ZSetOperations:zset 类型数据操作 (有序集合类型sortedset)

入门Demo

配置文件

  1. 构建maven工程
  2. 引入Spring相关依赖、引入JUnit依赖 还有Jedis和SpringDataRedis依赖
    pom.xml中引入jar包
<dependencies>
        <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>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.20.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
  1. 在 src/main/resources 下创建 properties 文件夹,建立 redis-config.properties,配置如下
# redis安装的ip地址
redis.host=127.0.0.1
# 默认端口号
redis.port=6379
# 密码,一般是没有设置的
redis.pass=
# 数据库的数量,默认为0
redis.database=0
# 最大空闲数
redis.maxIdle=300
# 最大等待时间
redis.maxWait=3000
# 在提取一个 jedis 实例时,是否提前进行验证操作;如果为 true,则得到的 jedis实例均是可用的
redis.testOnBorrow=true
  1. 在 src/main/resources 下创建 spring 文件夹 ,创建 applicationContext-redis.xml
<!--导入配置文件-->
    <context:property-placeholder location="classpath*:properties/*.properties"/>

    <!--redis 相关配置-->
    <!--maxIdle: 最大空闲数 maxWaitMillis:连接时的最大等待毫秒数
        testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>
    <!--创建Jedis连接工厂-->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:poolConfig-ref="poolConfig"/>
    <!--将工厂对象注入RedisTemplate中-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
    </bean>

测试练习

1.简单K-V操作

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

    @Autowired
    private RedisTemplate redisTemplate;

    @org.junit.Test
    public void setValue() {
        //创建一个key-value
        redisTemplate.boundValueOps("name").set("bestWaving");
    }

    @org.junit.Test
    public void getValue() {
        //通过key获取value
        String name = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }

    @org.junit.Test
    public void deleteValue() {
        //通过key删除value
        redisTemplate.delete("name");
    }
}

2.set 类型数据操作

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

    @Autowired
    //如果通过key删除不了value,要在这里添加泛型如:private RedisTemplate<Object,Object> redisTemplate;
    private RedisTemplate redisTemplate;

    @org.junit.Test
    public void setValue() {
        //通过set集合名字添加value值
        redisTemplate.boundSetOps("nameSet").add("吕布");
        redisTemplate.boundSetOps("nameSet").add("貂蝉");
        redisTemplate.boundSetOps("nameSet").add("小乔");
    }

    @org.junit.Test
    public void getValue() {
        //通过集合名字获取成员值
        Set name = redisTemplate.boundSetOps("nameSet").members();
        System.out.println(name);
    }

    @org.junit.Test
    public void deleteValue() {
        //删除成员中的某一个value值
        redisTemplate.boundSetOps("nameSet").remove("吕布");
        redisTemplate.boundSetOps("nameSet").remove("貂蝉");
    }

    @Test
    public void deleteAllValue() {
        //删除全部成员
        redisTemplate.delete("nameSet");
    }
}

3.针对 list 类型的数据操作

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

    @Autowired
    //如果删除key删除不了,要在这里添加泛型
    private RedisTemplate redisTemplate;

    @Test
    public void setValueRight() {
        //右插入
        redisTemplate.boundListOps("nameList1").rightPush("刘备");
        redisTemplate.boundListOps("nameList1").rightPush("关羽");
        redisTemplate.boundListOps("nameList1").rightPush("张飞");
    }

    @Test
    public void setValueLeft() {
        //左插入
        redisTemplate.boundListOps("nameList2").leftPush("刘备");
        redisTemplate.boundListOps("nameList2").leftPush("关羽");
        redisTemplate.boundListOps("nameList2").leftPush("张飞");
    }

    @Test
    public void getValue() {
        //根据key获取有序list集合的值,参数中0表示从左侧第一个开始,-1表示右侧第一个,这样就全概括了
        List list1 = redisTemplate.boundListOps("nameList2").range(0, -1);
        System.out.println(list1);
    }

    @Test
    //根据索引查询元素
    public void searchByIndex() {
        //索引从0开始,1是第二个
        String s = (String) redisTemplate.boundListOps("nameList2").index(1);
        System.out.println(s);
    }

    @Test
    public void deleteValue() {
        //remove中第一个参数是指定移除的个数
        redisTemplate.boundListOps("nameList2").remove(1 ,"关羽");
    }

    @Test
    public void deleteAllValue() {
        //删除所有
        redisTemplate.delete("nameList2");
    }

4.针对Hash类型的操作

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

    @Autowired
    private RedisTemplate redisTemplate;

    @org.junit.Test
    public void setValue() {
        //以键值对的形式添加元素 如:"a" : "吕布"
        redisTemplate.boundHashOps("nameHash").put("a", "吕布");
        redisTemplate.boundHashOps("nameHash").put("c", "大乔");
        redisTemplate.boundHashOps("nameHash").put("b", "小乔");
        redisTemplate.boundHashOps("nameHash").put("d", "貂蝉");
    }

    @org.junit.Test
    public void getValue() {
        //获取所有键
        Object o = redisTemplate.boundHashOps("nameHash").keys();
        System.out.println(o);
        //获取所有值
        List nameHash = redisTemplate.boundHashOps("nameHash").values();
        System.out.println(nameHash);
    }

    @org.junit.Test
    public void getValueByKey() {
        //根据key获取值
        Object o = redisTemplate.boundHashOps("nameHash").get("a");
        System.out.println(o);
    }

    @org.junit.Test
    public void deleteByKey() {
        //根据key获取值
        redisTemplate.boundHashOps("nameHash").delete("b");
    }

    @org.junit.Test
    //根据集合名字移除所有(注意:这个是大KEY,不是集合中的小key)
    public void deleteValue() {
        redisTemplate.delete("nameHash");
    }
}

5. zset 类型数据操作 (有序集合类型sortedset)

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

    @Autowired
    private RedisTemplate redisTemplate;

    @org.junit.Test
    public void setValue() {
        //创建一个key,为每个值定义一个分数
        redisTemplate.boundZSetOps("mySort").add("大乔", 80);
        redisTemplate.boundZSetOps("mySort").add("吕布", 20);
        redisTemplate.boundZSetOps("mySort").add("小乔", 60);
        redisTemplate.boundZSetOps("mySort").add("貂蝉", 100);
    }

    @org.junit.Test
    public void getValue() {
        //通过key获取value
        Set mySort = redisTemplate.boundZSetOps("mySort").range(0, -1);
        System.out.println(mySort);
        //跟随分数一起获取值,参数中0是最小值,200是最大值,自己定
        Set<ZSetOperations.TypedTuple> mySort1 = redisTemplate.boundZSetOps("mySort").rangeByScoreWithScores(0, 200);
        for (ZSetOperations.TypedTuple typedTuple : mySort1) {
            System.out.println(typedTuple.getValue() + "+++" + typedTuple.getScore());
        }
    }

    @org.junit.Test
    public void deleteValue() {
        //通过key删除value
        redisTemplate.delete("mySort");
    }
}

小结

这是个非常简单的Demo测试,没啥好说的,注意测试的时候将redis打开哦!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值