SpringDataRedis的簡單入門


Jedis

  Jedis是Redis官方推出的一款面向java的客戶端,提供了很多接口供java語言調用,可以在Redis官網下載,當然還有一些開源愛好者提供的客戶端,如Jredis SRP等,推薦使用JRedis.

SpringDataRedis

  SpringDataRedis是spring大家族中的一部分,提供了在spring應用中通過簡單的配置訪問redis服務,對redis底層開發包(Jedis,JRedis,andRJC)進行了高度封裝,RedisTemplate提供了redis各種操作,異常處理及序列化,支持發布訂閱,並對Spring3.1cache進行了實現.

SpringDataRedis針對Jedis提供了如下功能:

  1.連接池自動管理,提供了一個高度封裝的RedisTemplate類

  2.針對Jedis客戶端中大量api進行了歸類封裝,將同一類型操作封裝為operation接口

ValueIoerations:簡單K-V操作

SetIOperations:set類型數據操作.

ZSetOperations:zset類型數據操作

HashOperations:針對map類型的數據操作

ListOperations:針對list類型的數據操作.

SpringDataRedis入門小Demo

4.5.1准備工作

構建Maven工程  SpringDataRedisDemo   jar工程

引入Spring相關依賴、引入JUnit依賴   (內容參加其它工程)

引入Jedis和SpringDataRedis依賴

<!-- Spring -->
 <dependencies>
     <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.2.4.RELEASE</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>
<build>
        <plugins>            
            <!-- java編譯插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
</build>

在src/main/resources下創建properties文件夾,建立redis-config.properties

redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true

在src/main/resources下創建spring文件夾 ,創建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:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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>

maxIdle :最大空閑數

maxWaitMillis:連接時的最大等待毫秒數

testOnBorrow:在提取一個jedis實例時,是否提前進行驗證操作;如果為true,則得到的jedis實例均是可用的;

值類型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestValue {
    @Autowired
    private RedisTemplate redisTemplate;    
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("qingmu");        
    }    
    @Test
    public void getValue(){
        String str = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(str);
    }    
    @Test
    public void deleteValue(){
        redisTemplate.delete("name");;
    }    
}

 Set類型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/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(){
        Set members = redisTemplate.boundSetOps("nameset").members();
        System.out.println(members);
    }
    
    /**
     * 刪除集合中的某一個值
     */
    @Test
    public void deleteValue(){
        redisTemplate.boundSetOps("nameset").remove("孫權");
    }
    
    /**
     * 刪除整個集合
     */
    @Test
    public void deleteAllValue(){
        redisTemplate.delete("nameset");
    }
}

 List類型操作

創建測試類TestList

(1)右壓棧

/**
     * 右壓棧:后添加的對象排在后邊
     */
    @Test
    public void testSetValue1(){        
        redisTemplate.boundListOps("namelist1").rightPush("劉備");
        redisTemplate.boundListOps("namelist1").rightPush("關羽");
        redisTemplate.boundListOps("namelist1").rightPush("張飛");        
    }
    
    /**
     * 顯示右壓棧集合
     */
    @Test
    public void testGetValue1(){
        List list = redisTemplate.boundListOps("namelist1").range(0, 10);
        System.out.println(list);
    }

運行結果:

[劉備, 關羽, 張飛]

(2)左壓棧

    /**
     * 左壓棧:后添加的對象排在前邊
     */
    @Test
    public void testSetValue2(){        
        redisTemplate.boundListOps("namelist2").leftPush("劉備");
        redisTemplate.boundListOps("namelist2").leftPush("關羽");
        redisTemplate.boundListOps("namelist2").leftPush("張飛");        
    }
    
    /**
     * 顯示左壓棧集合
     */
    @Test
    public void testGetValue2(){
        List list = redisTemplate.boundListOps("namelist2").range(0, 10);
        System.out.println(list);
    }

運行結果:

[張飛, 關羽, 劉備]

(3)根據索引查詢元素

    /**
     * 查詢集合某個元素
     */
    @Test
    public void testSearchByIndex(){
        String s = (String) redisTemplate.boundListOps("namelist1").index(1);
        System.out.println(s);
    }

(4)移除某個元素的值

    /**
     * 移除集合某個元素
     */
    @Test
    public void testRemoveByIndex(){
        redisTemplate.boundListOps("namelist1").remove(1, "關羽");
    }

 Hash類型操作

創建測試類TestHash

(1)存入值

    @Test
    public void testSetValue(){
        redisTemplate.boundHashOps("namehash").put("a", "唐僧");
        redisTemplate.boundHashOps("namehash").put("b", "悟空");
        redisTemplate.boundHashOps("namehash").put("c", "八戒");
        redisTemplate.boundHashOps("namehash").put("d", "沙僧");
    }

2)提取所有的KEY

    @Test
    public void testGetKeys(){
        Set s = redisTemplate.boundHashOps("namehash").keys();        
        System.out.println(s);        
    }

運行結果:

[a, b, c, d]

(3)提取所有的值

    @Test
    public void testGetValues(){
        List values = redisTemplate.boundHashOps("namehash").values();
        System.out.println(values);        
    }

運行結果:

[唐僧, 悟空, 八戒, 沙僧]

 

4)根據KEY提取值

    @Test
    public void testGetValueByKey(){
        Object object = redisTemplate.boundHashOps("namehash").get("b");
        System.out.println(object);
    }

運行結果:

悟空

 

5)根據KEY移除值

    @Test
    public void testRemoveValueByKey(){
        redisTemplate.boundHashOps("namehash").delete("c");
    }

運行后再次查看集合內容:

 

[唐僧, 悟空, 沙僧]

 

    @Test

    publicvoid testGetValues(){

        List values = redisTemplate.boundHashOps("namehash").values();

        System.out.println(values);    

    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM