1. 程式人生 > >Spring Data Redis框架使用

Spring Data Redis框架使用

一、Spring-Data-Redis:是Spring家族的一部分,提供了在Spring應用中通過簡單的配置訪問Redis服務,對Redis底層開發包(Jedis、JRedis、and JRC)進行了高度封裝,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型別的資料操作。 三、需要依賴的jar包如下:

	<!-- 快取 -->
	<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>

四、在src/main/resource中建立properties資料夾,建立redis-config.properties

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

五、在src/main/resource中建立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: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">  
     <!-- maxIdle :最大空閒數 -->
     <property name="maxIdle" value="${redis.maxIdle}" />   
     <!-- maxWaitMillis:連線時的最大等待毫秒數 -->
     <property name="maxWaitMillis" value="${redis.maxWait}" />  
     <!-- testOnBorrow:在提取一個jedis例項時,是否提前進行驗證操作;如果為true,則得到的jedis例項均是可用的; -->
     <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>  

六、String值型別操作

package com.yintong.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;

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

}

結果顯示:

七 、Set資料型別操作

package com.yintong.test;

import java.util.Set;

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class SetDemo {
	@Autowired
	private RedisTemplate redisTemplate;
	/**
	 * 存入值:Bound系列操作示例,Bound系列操作的優勢在於只需要繫結一次,然後可以進行一個系列的操作,程式碼十分精煉。
	 */
	@Test
	public void setValue() {//redis中設定值
		BoundSetOperations boundSetOps = redisTemplate.boundSetOps("nameSet");
		boundSetOps.add("zzx");
		boundSetOps.add("love");
		boundSetOps.add("fj");
	}
	/**
	 * 提取值
	 */
	@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型別操作:

package com.yintong.test;

import java.util.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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestList {
	@Autowired
	private RedisTemplate redisTemplate;
	/**
	 * 右壓棧:後新增的物件排在後邊
	 */
	@Test
	public void setValueList() {
		redisTemplate.boundListOps("nameList").rightPush("zzx");
		redisTemplate.boundListOps("nameList").rightPush("fj");
	}
	/**
	 * 顯示右壓棧集合
	 */
	@Test
	public void getValueList() {
		List range = redisTemplate.boundListOps("nameList").range(0, -1);
		System.out.println(range);
	}
	/**
	 * 左壓棧:後新增的物件排在前邊
	 */
	@Test
	public void testSetValue2(){	
		redisTemplate.boundListOps("nameList").leftPush("love");
	}
	/**
	 * 查詢集合某個元素
	 */
	@Test
	public void testSearchByIndex(){
		Object index = redisTemplate.boundListOps("nameList").index(1);
		System.out.println(index);
	}
	/**
	 * 移除集合某個元素
	 */
	@Test
	public void testRemoveByIndex(){
		redisTemplate.boundListOps("nameList").remove(1, "zzx");
	}
}

九、Hash型別操作:

package com.yintong.test;

import java.util.List;
import java.util.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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestHash {
	@Autowired
	private RedisTemplate redisTemplate;
	//插入值
	@Test
	public void setValue() {
		redisTemplate.boundHashOps("nameHash").put("zzx", "boy");
		redisTemplate.boundHashOps("nameHash").put("fj", "girl");
	}
	//提取所有的KEY
	@Test
	public void getKey() {
		Set keys = redisTemplate.boundHashOps("nameHash").keys();
		System.out.println(keys);
	}
	//獲取所有值
	@Test
	public void getValues() {
		List values = redisTemplate.boundHashOps("nameHash").values();
		System.out.println(values);
	}
	@Test
	//根據key獲取值(常用)
	public void getValueByKey() {
		Object nameValue = redisTemplate.boundHashOps("nameHash").get("zzx");
		System.out.println(nameValue);
	}
	@Test
	//根據key溢位值
	public void deleteKey() {
		redisTemplate.boundHashOps("nameHash").delete("zzx");
	}
}