1. 程式人生 > >Spring-data-redis入門

Spring-data-redis入門

1.簡介

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

2.入門小Demo

1.準備工作

(1)構建Maven工程

(2)引入Spring相關依賴、引入JUnit依賴

(3)引入Jedis和SpringDataRedis依賴

<properties>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>
​
    <dependencies>
    <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>
​
        <!-- 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>
    </dependencies>

(4)在src/main/resources下建立properties資料夾,建立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
# 控制一個pool最多有多少個狀態為idle(空閒的)的jedis例項 
redis.maxIdle=300
# 表示當borrow(引入)一個jedis例項時,最大的等待時間,如果超過等待時間(毫秒),則直接丟擲JedisConnectionException;  
redis.maxWait=3000
# 在borrow一個jedis例項時,是否提前進行validate操作;如果為true,則得到的jedis例項均是可用的  
redis.testOnBorrow=true

(5)在src/main/resources下建立spring資料夾 ,建立applicationContext-redis.xml

<context:property-placeholder location="classpath*:properties/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>
    <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>

2.值型別操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestValue {
​
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 存值
     */
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("redis");
    }
​
    /**
     * 取值
     */
    @Test
    public void getValue(){
        System.out.println(redisTemplate.boundValueOps("name").get());
    }
​
    /**
     * 刪除
     */
    @Test
    public void delValue(){
        redisTemplate.delete("name");
    }
}

3.set

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestSet {
​
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 存值
     */
    @Test
    public void setValue(){
        redisTemplate.boundSetOps("books").add("西遊記");
        redisTemplate.boundSetOps("books").add("三國演義");
        redisTemplate.boundSetOps("books").add("紅樓夢");
        redisTemplate.boundSetOps("books").add("水滸傳");
    }
​
    /**
     * 取值
     * set型別為無序的,存取順序不一致
     */
    @Test
    public void getValue(){
        Set books = redisTemplate.boundSetOps("books").members();
        System.out.println(books); //[西遊記, 水滸傳, 紅樓夢, 三國演義]
    }
​
    /**
     * 刪除集合中的某個值
     */
    @Test
    public void deleValue(){
        redisTemplate.boundSetOps("books").remove("西遊記");
    }
​
    /**
     * 刪除整個集合
     */
    @Test
    public void deleAll(){
        redisTemplate.delete("books");
    }
}

4.List型別操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestList {
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 右壓棧:後新增的物件排在後邊
     */
    @Test
    public void setValue() {
        redisTemplate.boundListOps("nameList").rightPush("劉備");
        redisTemplate.boundListOps("nameList").rightPush("關羽");
        redisTemplate.boundListOps("nameList").rightPush("張飛");
    }
​
    /**
     * 顯示右壓棧集合
     */
    @Test
    public void getValue() {
        //range(long start,long end)
        //start表示開始的索引,end表示要遍歷的長度
        List nameList = redisTemplate.boundListOps("nameList").range(0, 3);
        System.out.println(nameList);   //[劉備, 關羽, 趙飛]
    }
​
    /**
     * 左壓棧:先新增的物件排在後邊
     */
    @Test
    public void setValue1() {
        redisTemplate.boundListOps("nameList1").leftPush("宋江");
        redisTemplate.boundListOps("nameList1").leftPush("武松");
        redisTemplate.boundListOps("nameList1").leftPush("魯智深");
    }
​
    /**
     * 顯示左壓棧集合
     */
    @Test
    public void getValue1() {
        List nameList = redisTemplate.boundListOps("nameList1").range(0, 3);
        System.out.println(nameList);   //[魯智深, 武松, 宋江]
    }
​
    /**
     * 查詢某個結果
     */
    @Test
    public void getSerarchByIndex() {
        Object o = redisTemplate.boundListOps("nameList").index(1);
        System.out.println(o);  //關羽
    }
​
    /**
     * 移除集合中的某個元素
     */
    @Test
    public void removeByIndex() {
        //remove(long i,Object value)
        //i表示要刪除的元素個數,value表示要刪除的元素
        //此處表示刪除1個魯智深
        redisTemplate.boundListOps("nameList1").remove(1, "魯智深");
    }
}
​

5.Hash型別操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestHash {
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 存入值
     */
    @Test
    public void setValue(){
        redisTemplate.boundHashOps("city").put("山西","太原");
        redisTemplate.boundHashOps("city").put("河北","石家莊");
        redisTemplate.boundHashOps("city").put("浙江","杭州");
        redisTemplate.boundHashOps("city").put("山東","青島");
        redisTemplate.boundHashOps("city").put("內蒙古","呼和浩特");
    }
​
    /**
     * 獲取所有的key
     */
    @Test
    public void getKeys(){
        Set cityKey = redisTemplate.boundHashOps("city").keys();
        System.out.println(cityKey);
    }
​
    /**
     * 獲取所有的value
     */
    @Test
    public void getValues(){
        List cityValue = redisTemplate.boundHashOps("city").values();
        System.out.println(cityValue);
    }
​
    /**
     * 獲取指定的value
     */
​
    @Test
    public void getValue(){
        Object o = redisTemplate.boundHashOps("city").get("山西");
        System.out.println(o);
    }
​
    /**
     * 根據key移除value
     */
​
    @Test
    public void delete(){
        redisTemplate.boundHashOps("city").delete("內蒙古");
    }
}
​