天天看點

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概述

Jedis是Redis官方推出的一款面向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");
    }
}
           

繼續閱讀