Spring Data Redis

36 篇文章 0 订阅
5 篇文章 0 订阅

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

 

Spring Data Redis 入门demo

1、引入Spring Data Redis 依赖,包括测试需要的Junit

<?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>demo</groupId>
    <artifactId>springdataredis</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>

 

2、添加相关配置文件

(1)redis-config.properties

# Redis settings 
# server IP 
redis.host=127.0.0.1
# server port 
redis.port=6379
# server pass 
redis.pass=
# use dbIndex 
redis.database=0
# \u63A7\u5236\u4E00\u4E2Apool\u6700\u591A\u6709\u591A\u5C11\u4E2A\u72B6\u6001\u4E3Aidle(\u7A7A\u95F2\u7684)\u7684jedis\u5B9E\u4F8B 
redis.maxIdle=300
# \u8868\u793A\u5F53borrow(\u5F15\u5165)\u4E00\u4E2Ajedis\u5B9E\u4F8B\u65F6\uFF0C\u6700\u5927\u7684\u7B49\u5F85\u65F6\u95F4\uFF0C\u5982\u679C\u8D85\u8FC7\u7B49\u5F85\u65F6\u95F4(\u6BEB\u79D2)\uFF0C\u5219\u76F4\u63A5\u629B\u51FAJedisConnectionException\uFF1B  
redis.maxWait=3000
# \u5728borrow\u4E00\u4E2Ajedis\u5B9E\u4F8B\u65F6\uFF0C\u662F\u5426\u63D0\u524D\u8FDB\u884Cvalidate\u64CD\u4F5C\uFF1B\u5982\u679C\u4E3Atrue\uFF0C\u5219\u5F97\u5230\u7684jedis\u5B9E\u4F8B\u5747\u662F\u53EF\u7528\u7684  
redis.testOnBorrow=true

(2)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*:properties/*.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>  
  
   <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>  

 

(3)部分说明

maxIdle :最大空闲数

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

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

 

(4)值类型操作

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 值类型操作
 * Author xushuai
 * Description
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestValue {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置值
     */
    @Test
    public void setValue() {
        redisTemplate.boundValueOps("test").set("hello spring data redis");
    }

    /**
     * 获取值
     */
    @Test
    public void getValue() {
        String value = (String) redisTemplate.boundValueOps("test").get();
        System.out.println(value);
    }

    /**
     * 删除指定键的值
     */
    @Test
    public void deleteValue() {
        redisTemplate.delete("test");
    }

}

 

(5)Set类型操作

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Set;

/**
 * Set类型操作
 * Author xushuai
 * Description
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestSet {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置值
     */
    @Test
    public void setValue() {
        redisTemplate.boundSetOps("set").add("tom");
        redisTemplate.boundSetOps("set").add("jack");
        redisTemplate.boundSetOps("set").add("rose");
    }

    /**
     * 获取值
     */
    @Test
    public void getValue() {
        Set set = redisTemplate.boundSetOps("set").members();
        System.out.println(set);
    }

    /**
     * 删除指定键的值
     */
    @Test
    public void deleteValue() {
        // 删除固定值
        redisTemplate.boundSetOps("set").remove("jack");
        // 删除全部
        redisTemplate.delete("set");
    }
}

 

(6)List类型操作

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

/**
 * List类型操作
 * Author xushuai
 * Description
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestList {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置值
     */
    @Test
    public void setValue() {
        // 左压栈:存入List的开始
        redisTemplate.boundListOps("list").leftPush("3");
        redisTemplate.boundListOps("list").leftPush("2");
        redisTemplate.boundListOps("list").leftPush("1");
        // 右压栈:存入List的末尾
        redisTemplate.boundListOps("list").rightPush("1");
        redisTemplate.boundListOps("list").rightPush("2");
        redisTemplate.boundListOps("list").rightPush("3");
    }

    /**
     * 获取值
     */
    @Test
    public void getValue() {
        // 获取 下标0-2的值
        List list = redisTemplate.boundListOps("list").range(0, 10);
        // 获取指定下标的值
        long index = 1;
        String value = (String) redisTemplate.boundListOps("list").index(index);
        System.out.println("集合:" + list);
        System.out.println("下标[" + index  + "]" + value);
    }

    /**
     * 删除指定键的值
     */
    @Test
    public void deleteValue() {
        // 左弹栈:并返回弹出的值
        String leftPop = (String) redisTemplate.boundListOps("list").leftPop();
        System.out.println("leftPop:" + leftPop);
        // 右弹栈:并返回弹出的值
        String rightPop = (String) redisTemplate.boundListOps("list").rightPop();
        System.out.println("rightPop:" + rightPop);
        // 删除全部
        redisTemplate.delete("list");
    }
}

 

(7)Hash类型操作

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Hash类型操作
 * Author xushuai
 * Description
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestHash {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置值
     */
    @Test
    public void setValue() {
        redisTemplate.boundHashOps("hash").put("一","A");
        redisTemplate.boundHashOps("hash").put("二","B");
        redisTemplate.boundHashOps("hash").put("三","C");
    }

    /**
     * 获取值
     */
    @Test
    public void getValue() {
        // 获取指定key的值
        String value1 = (String) redisTemplate.boundHashOps("hash").get("一");
        System.out.println(value1);
        
        /*
         * 获取所有的值
         */
        List hashValues = redisTemplate.boundHashOps("hash").values();
        System.out.println(hashValues);

        /*
         * 获取所有的键值,格式如下(无序):
         *            {三=C, 一=A, 二=B}
         *
         */
        Map hash = redisTemplate.boundHashOps("hash").entries();
        System.out.println(hash);
    }

    /**
     * 获取键
     * 返回 [一, 二, 三]
     */
    @Test
    public void getKey() {
        // 获取指定key的值
        Set hashKey = redisTemplate.boundHashOps("hash").keys();
        System.out.println(hashKey);
    }

    /**
     * 删除指定键的值
     */
    @Test
    public void deleteValue() {
        // 删除指定key的值
        redisTemplate.boundHashOps("hash").delete("二");
        // 删除全部
        redisTemplate.delete("hash");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值