1. 程式人生 > >spring-data-redis的基本使用

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型別的資料操作

首先,需要在虛擬機器安裝一個redis資料庫,安裝 ,我電腦安裝redis資料庫的主機地址是:192.168.5.111

其次:為了更直觀的看reids中的資料變化,所以最好下載一個工具  RedisDesktopManager 可以直觀的看到資料有沒有在redis資料庫中

第一步:導包

在pom檔案中需要匯入:spring相關的jar包,srping-data-redis的包,再匯入兩個測試包,方便測試

<?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">
    <parent>
        <artifactId>demo</artifactId>
        <groupId>cn.itcast.demo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring_data_redis</artifactId>
    <!--規定版本-->
    <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>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>
        <!--spring-data-redis包-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.7.RELEASE</version>
        </dependency>
        <!--測試的兩個-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>

第二步:引入spring-data-redis的配置檔案  redis-config.properties

#裝有redis資料庫的虛擬機器中的一臺機器的ip
redis.host=192.168.5.111
redis.port=6379
redis.pass=
#預設儲存在databse[0]資料庫, redis的database相當於一個數據,預設也是0
redis.database=0
#maxIdle:最大空閒數
redis.maxIdle=300
#maxWait:最大等待時長,3秒
redis.maxWait=3000
#testOnBorrow:在提取一個jedis例項時,是否提前進行驗證操作;如果為true,則得到的jedis例項均是可用的;
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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       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">

    <!--1引入配置資訊-->
    <context:property-placeholder location="classpath*:properties/*.properties"/>

   <!--2配置redis,相當於例項化了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>

    <!--3獲取redis的連線工廠-->
    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="${redis.host}" p:password="${redis.pass}" p:port="${redis.port}" p:poolConfig-ref="poolConfig"/>

    <!--獲取redisTemplate,template需要redis連線工廠-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
          <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>

</beans>

第四步:開始使用redisTemplate進行各型別的CURD操作

package spring_data_redis_test;

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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext_redis.xml")
public class AllTest {
    //注入template物件
    @Autowired
    private RedisTemplate redisTemplate;
//----------------------Hash型別的操作:經常用---------------------------------
//(1)存入值
@Test
public void  boundHashOpsSet(){
    redisTemplate.boundHashOps("namehash").put("country1","中國");
    redisTemplate.boundHashOps("namehash").put("country2","日本");
    redisTemplate.boundHashOps("namehash").put("country3","韓國");
}
//(2)提取所有的KEY
@Test
public void  boundHashOpsKeys(){
    Set keys = redisTemplate.boundHashOps("namehash").keys();
    System.out.println(keys);
}
//(3)提取所有的值
@Test
public void boundHashOpsValues(){
    List values = redisTemplate.boundHashOps("namehash").values();
    System.out.println(values);
}
//(4) 根據KEY提取值
@Test
public void boundHashOpsByKey(){
    Object name = redisTemplate.boundHashOps("namehash").get("country1");
    System.out.println(name);
}
//根據KEY移除值
@Test
public void boundHashOpsDelByKey(){
    redisTemplate.boundHashOps("namehash").delete("country2");
}
//----------------------------值型別的操作:因為運算元量少,所以不長用---------------------------------
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("王五");
    }
    @Test
    public void getValue(){
        Object name = redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }
    @Test
    public void deleteValue(){
        redisTemplate.delete("name");
    }

//----------------------set型別的操作:因為運算元量少,所以不長用---------------------------------
    /**
     * 存入值
     */
    @Test
    public void boundSetOpsAdd(){
    redisTemplate.boundSetOps("nameset").add("曹操"); //放入值
    redisTemplate.boundSetOps("nameset").add("劉備");
    redisTemplate.boundSetOps("nameset").add("孫權");
    }
    /**
     * 提取值
     */
    @Test
    public void boundSetOpsGet(){
        Set names= redisTemplate.boundSetOps("nameset").members();//取出值
        System.out.println(names);
    }
    /**
     * 刪除集合中的某一個值
     */
    @Test
     public void boundSetOpsDelete(){
         redisTemplate.boundSetOps("nameset").remove("曹操");
     }

    /**
     * 刪除整個集合
     */
    @Test
    public void boundSetOpsDeleteAll(){
        redisTemplate.delete("nameset");
    }

    //----------------------list型別的操作:因為運算元量少,所以不長用---------------------------------
    /**
     * 右壓棧:後新增的物件排在後邊
     * 右壓棧用的多,因為快,原理是
     */
    @Test
    public void boundListrightPush(){
        redisTemplate.boundListOps("namelist").rightPush("趙子龍");
        redisTemplate.boundListOps("namelist").rightPush("張飛");
        redisTemplate.boundListOps("namelist").rightPush("關羽");
    }
    /**
     * 顯示右壓棧集合
     */
    @Test
    public void boundListRange(){
        List namelist = redisTemplate.boundListOps("namelist").range(0, 10);
        System.out.println(namelist);
    }
    

    /**
     * 查詢:根據索引查詢集合某個元素
     */
    @Test
    public void boundListIndex(){
        Object name = redisTemplate.boundListOps("namelist").index(1);
        System.out.println(name);
    }

    /**
     * 刪除: 根據值移除集合某個元素
     */
    @Test
    public void  bondListRemove(){
        redisTemplate.boundListOps("namelist").remove(1,"關羽");
    }
    /**
     * 刪除: 刪除全部
     */
    @Test
    public void  bondListDelete(){
        redisTemplate.delete("namelist");
    }

}