SringDataRedis的简单使用

** SpringDataRedis简介:** <Excerpt in index | 首页摘要>

<The rest of contents | 余下全文>

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


Redis概述

Redis是一款开源的高性能Key-Value数据库,运行在内存中,由ANSI C编写。企业开发通常采用Redis来实现缓存。

Jedis概述

JedisRedis官方推出的一款面向Java的客户端,提供了很多接口供Java语言调用。可以在Redis官网下载,当然还有一些开源爱好者提供的客户端,如Jredis、SRP等等,推荐使用Jedis。

Spring Data Redis概述

spring-data-redis针对jedis提供了如下功能:
1.连接池自动管理,提供了一个高度封装的“RedisTemplate”类
2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口

  • ValueOperations:简单K-V操作
  • ValueOperations:简单K-V操作
  • SetOperations:set类型数据操作
  • ZSetOperations:zset类型数据操作
  • HashOperations:针对map类型的数据操作
  • ListOperations:针对list类型的数据操作

初步环境搭建

创建Maven工程

核心依赖:

  • redis.clients
  • spring-data-redis
  • junit
  • 以及spring相关jar包

POM依赖参考代码

<properties>
    <spring.version>4.2.4.RELEASE</spring.version>
</properties>
<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
</dependencies>

本pom文件可以在普通工程中,若是在其他工程中搭建SpringDataRedis,请自行添加所需依赖

添加配置文件

  • redis-config.properties
  • applicationContext-redis.xml

redis-config.properties参考代码

# Redis settings 
# 服务ip
redis.host=127.0.0.1
# 服务端口
redis.port=6379
# 服务密码,没有设置密码无需配置
redis.pass=
# 使用的数据库索引
redis.database=0
# 最大能保持空闲状态的连接数
redis.maxIdle=300
# 当池中没有返回链接时,最大的等待时间
redis.maxWait=3000
# 当调用borrow Object方法时,是否进行有效性检查
redis.testOnBorrow=true

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"
       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*:redis-config.properties"/>
    <!-- redis 相关配置 -->
    <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: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>  

简单key-value的增删改

TestValue类示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestValue {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("王小明");
    }
    @Test
    public void getValue(){
        String name = (String) redisTemplate.boundValueOps("name").get();
    }
    @Test
    public void deleteValue(){
        /**
        *使用redisTemplate的delete()方法删除指定key的value
        *该api有两个重载方法
        *delete(String key);
        *delete(Collection keys);
        */
        redisTemplate.delete("name");
        redisTemplate.delete(Arrays.asList(new String[]{"name1","name2"}));
    }
}

boundValueOps(String key).set(Object obj);方法可以存储任意对象,不仅仅是String类型

Set类型的增删改

TestSet类示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath: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(){
        /**
         * 使用boundSetOps绑定key后,调用members获取set集合
         */
        Set nameSet = redisTemplate.boundSetOps("nameSet").members();
    }
    @Test
    public void remove(){
        redisTemplate.boundSetOps("nameSet").remove("曹操");
    }
    @Test
    public void delete(){
        redisTemplate.delete("nameSet");
    }
}

注意:

1.使用boundSetOps(String key).add(Object obj);方法添加对象时,默认该key对应就是一个Set集合!

示例类演示的setValue()方法结果为:

===============================

[曹操, 孙权, 刘备]

===============================

错误操作

HashSet set = new HastSet();
set.add("曹操");
set.add("刘备");
set.add("孙权");
redisTemplate.boundSetOps("nameSet").add(set);

此时结果结果为

=====================

[ [曹操, 孙权, 刘备] ]

=====================

List类型的增删改

TestList类示例

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestList {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void right(){
        redisTemplate.boundListOps("nameList").rightPush("1");
        redisTemplate.boundListOps("nameList").rightPush("2");
    }
    @Test
    public void left(){
        redisTemplate.boundListOps("nameList").leftPush("5");
        redisTemplate.boundListOps("nameList").leftPush("6");
    }
    @Test
    public void getList(){
        /**
         * 对于range(Long start,Long end);
         * start:从start开始获取
         * end:在end结束
         * 如果要获取全部的list,只有将end设置的非常大,没有其他api可以获取全部的list
         */
        List list = redisTemplate.boundListOps("nameList").range(0, 10);
    }
    @Test
    public void getValue(){
        /**
         * index(Long index);获取list的指定索引为index的对象
         */
        Object o = redisTemplate.boundListOps("nameList").index(1);
    }
    @Test
    public void remove(){
        /**
         * remove(Long number,Object value);
         * number:要删除的个数
         * value:要删除的元素
         * 如果该集合中有多个value对象,使用number指定删除个数
         */
        redisTemplate.boundListOps("nameList").remove(1,"曹操" );
    }
    @Test
    public void delete(){
        redisTemplate.delete("nameList");
    }
}

对于boundListOps(String key)来说,还有leftPushAll(Collection value);以及rightPushAll(Collection value)等其他方法.

一般来说,只要理解leftPush(Object obj)和rightPush(Object obj);就行,其他api的用法也大致相同

如果你知道链表原理的话,这个其实原理是一样的

leftPush(Object obj);左压栈,从左侧压入对象

rightPush(Object obj);右压栈,从右侧压入对象

在执行完TestList示例类的left()与right()方法后,两个方法执行先后关系无影响

再调用getList(),返回的结果为

=======================

[6, 5, 1, 2]

=======================

由此一眼就能看懂左压栈和右压栈的区别

Hash类型的增删改

TestHash的类示例

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestHash {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void setValue(){
        redisTemplate.boundHashOps("name").put("1","曹操" );
        redisTemplate.boundHashOps("name").put("2","孙权" );
        redisTemplate.boundHashOps("name").put("3","周瑜" );
        redisTemplate.boundHashOps("name").put("4","刘备" );
    }
    @Test
    public void getKey(){
        /**
         * 获取key集合
         */
        Set name = redisTemplate.boundHashOps("name").keys();
    }

    @Test
    public void getValue(){
        /**
         * 获取值集合
         */
        List name = redisTemplate.boundHashOps("name").values();
    }
    @Test
    public void index(){
        /**
         * 获取指定的key
         */
        Object name = redisTemplate.boundHashOps("name").get("1");
    }
    @Test
    public void delete(){
        /**
         * 删除指定的key
         */
        redisTemplate.boundHashOps("name").delete("1");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值