J2ee項目從0搭建(十一):在項目中整合Redis,用於資料的儲存或者緩衝_redis

來源:互聯網
上載者:User
一、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 settingredis.hostName =192.168.240.131redis.port=6379redis.timeout=15000redis.usePool=trueredis.password=buildmavenweb#jedis settingjedis.maxIdle=6jedis.minEvictableIdleTimeMillis=300000jedis.numTestsPerEvictionRun=3jedis.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.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://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>


PS: 下面這段內容取自:http://shift-alt-ctrl.iteye.com/blog/1887370

 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. */@Componentpublic 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異常總結(持續收集中);或者留言我們共同討論。
八、推薦Redis學習地址:http://www.redis.net.cn/
====================================================================================================================== 為了便於大家學習,項目將被開源在我的github上: 項目地址:https://github.com/gubaijin/buildmavenweb
如何將項目開源道github,請看我的另一篇博文:GitHub上建立項目 並初始化本地工程提交到GitHub上






相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.