1. 程式人生 > >J2ee專案從0搭建(十一):在專案中整合Redis,用於資料的儲存或者快取

J2ee專案從0搭建(十一):在專案中整合Redis,用於資料的儲存或者快取

一、Redis安裝

已經安裝好redis的可以直接進入下一步,沒有的可以先進行安裝:Linux(CentOS 7)Redis 安裝

二、pom依賴:

Jedis是redis的java版本的客戶端實現
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.6.1</version>
		</dependency>

三、spring配置

在resources目錄下新建一個redis.properties:

#redis setting
redis.hostName =192.168.240.131
redis.port=6379
redis.timeout=15000
redis.usePool=true
redis.password=buildmavenweb

#jedis setting
jedis.maxIdle=6
jedis.minEvictableIdleTimeMillis=300000
jedis.numTestsPerEvictionRun=3
jedis.timeBetweenEvictionRunsMillis=60000

再建立一個spring-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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		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"
	   default-lazy-init="true">

	<context:component-scan base-package="com.spring.demo.redis" />

	<!-- 引入redis配置檔案 -->
	<context:property-placeholder location="classpath:redis.properties" />

	<!-- 連線池配置 -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<!-- 連線池中最大空閒的連線數 -->
		<property name="maxIdle" value="${jedis.maxIdle}"></property>
		<!-- 連線空閒的最小時間,達到此值後空閒連線將可能會被移除。負值(-1)表示不移除. -->
		<property name="minEvictableIdleTimeMillis" value="${jedis.minEvictableIdleTimeMillis}"></property>
		<!-- 對於“空閒連結”檢測執行緒而言,每次檢測的連結資源的個數。預設為3 -->
		<property name="numTestsPerEvictionRun" value="${jedis.numTestsPerEvictionRun}"></property>
		<!-- “空閒連結”檢測執行緒,檢測的週期,毫秒數。如果為負值,表示不執行“檢測執行緒”。預設為-1. -->
		<property name="timeBetweenEvictionRunsMillis" value="${jedis.timeBetweenEvictionRunsMillis}"></property>
	</bean>

	<!-- Spring提供的Redis連線工廠 -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
		<!-- 連線池配置 -->
		<property name="poolConfig" ref="jedisPoolConfig"></property>
		<!-- Redis服務主機 -->
		<property name="hostName" value="${redis.hostName}"></property>
		<!-- Redis服務埠號 -->
		<property name="port" value="${redis.port}"></property>
		<!-- 連超時設定 -->
		<property name="timeout" value="${redis.timeout}"></property>
		<!-- 是否使用連線池 -->
		<property name="usePool" value="${redis.usePool}"></property>
		<!-- Redis服務連線密碼 -->
		<property name="password" value="${redis.password}"></property>
	</bean>

	<!-- Spring提供的訪問Redis類 -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<!-- Redis連線工廠 -->
		<property name="connectionFactory" ref="jedisConnectionFactory"></property>
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
		</property>
		<!-- JdkSerializationRedisSerializer支援對所有實現了Serializable的類進行序列化 -->
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
		</property>
	</bean>
</beans>

 spring-data-redis提供了多種serializer策略,這對使用jedis的開發者而言,實在是非常便捷。sdr提供了4種內建的serializer:

  • JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable介面,ObjectInputStrean,ObjectOutputStream),資料以位元組流儲存
  • StringRedisSerializer:字串編碼,資料以string儲存
  • JacksonJsonRedisSerializer:json格式儲存
  • OxmSerializer:xml格式儲存

    其中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎的序列化策略,其中“JacksonJsonRedisSerializer”與“OxmSerializer”都是基於stirng儲存,因此它們是較為“高階”的序列化(最終還是使用string解析以及構建java物件)。

    RedisTemplate中需要宣告4種serializer,預設為“JdkSerializationRedisSerializer”:

    1) keySerializer :對於普通K-V操作時,key採取的序列化策略
    2) valueSerializer:value採取的序列化策略
    3) hashKeySerializer: 在hash資料結構中,hash-key的序列化策略
    4) hashValueSerializer:hash-value的序列化策略

    無論如何,建議key/hashKey採用StringRedisSerializer。


四、web.xml中

如果配置檔案是統一的格式載入的,如:classpath:/spring-*.xml,就不許做特殊載入,否則需要將spring-redis.xml單獨載入進來
	<!-- 載入配置檔案 -->
	<!--contextConfigLocation在 ContextLoaderListener類中的預設值是 /WEB-INF/applicationContext.xml -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:/spring-*.xml
		</param-value>
	</context-param>


五、java程式碼中使用

新建一個RedisUtils.class,用來專門處理redis的相關操作:

package com.spring.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by ehsy_it on 2016/8/7.
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 得到指定key值的value
     * @param key
     */
    public Object get(String key){
        return redisTemplate.boundValueOps(key).get();
    }

    /**
     * 儲存指定key值的value
     * @param key
     * @param value
     */
    public void set(String key, Object value){
        redisTemplate.boundValueOps(key).set(value);
    }

    /**
     * 刪除指定key的value
     * @param key
     */
    public void del(String key){
        redisTemplate.delete(key);
    }
}

六、測試

新建一個RedisMain.class類,我們通過程式碼儲存一個String型別和list型別,並從中獲取出來:
package com.spring.demo.redis;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ehsy_it on 2016/8/7.
 */
public class RedisMain {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/spring-redis.xml");
        RedisUtils redisUtils = (RedisUtils) ctx.getBean("redisUtils");
        redisUtils.set("china","瓷器");
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        redisUtils.set("list", list);
        System.out.println("china=" + redisUtils.get("china"));
        System.out.println("list[1]=" + ((List)redisUtils.get("list")).get(1));
    }
}


七、異常 處理

整合中遇到問題可以檢視這裡解決:Redis異常總結(持續收集中);或者留言我們共同討論。 ======================================================================================================================

為了便於大家學習,專案將被開源在我的github上: