歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 深入理解Spring Redis的使用

深入理解Spring Redis的使用

日期:2017/3/1 9:27:52   编辑:Linux編程

關於spring redis框架的使用,網上的例子很多很多。但是在自己最近一段時間的使用中,發現這些教程都是入門教程,包括很多的使用方法,與spring redis豐富的api大相徑庭,真是浪費了這麼優秀的一個框架。這裡,我們就對比之前對spring orm中對hibernate的使用,來理解使用spring redis的使用。(本文章不做redis基本命令使用的講解)

Ubuntu 14.04下Redis安裝及簡單測試 http://www.linuxidc.com/Linux/2014-05/101544.htm

Redis集群明細文檔 http://www.linuxidc.com/Linux/2013-09/90118.htm

Ubuntu 12.10下安裝Redis(圖文詳解)+ Jedis連接Redis http://www.linuxidc.com/Linux/2013-06/85816.htm

Redis系列-安裝部署維護篇 http://www.linuxidc.com/Linux/2012-12/75627.htm

CentOS 6.3安裝Redis http://www.linuxidc.com/Linux/2012-12/75314.htm

Redis安裝部署學習筆記 http://www.linuxidc.com/Linux/2014-07/104306.htm

Redis配置文件redis.conf 詳解 http://www.linuxidc.com/Linux/2013-11/92524.htm

1. Redis使用場景

Redis是一個開源的使用ANSI C語言編寫、支持網絡、可基於內存亦可持久化的日志型、Key-Value數據庫,並提供多種語言的API。

我們都知道,在日常的應用中,數據庫瓶頸是最容易出現的。數據量太大和頻繁的查詢,由於磁盤IO性能的局限性,導致項目的性能越來越低。

這時候,基於內存的緩存框架,就能解決我們很多問題。例如Memcache,Redis等。將一些頻繁使用的數據放入緩存讀取,大大降低了數據庫的負擔。提升了系統的性能。

其實,對於hibernate的二級緩存,是同樣的道理。利用內存高速的讀寫速度,來解決硬盤的瓶頸。

2. 配置使用redis

首先,我們需要引入基本的jar包。maven中的基本引用如下:

    <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.2</version>
</dependency>

然後,在applicationContext中配置如下:

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>

<bean id="connectionFactory" 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="stringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<!-- 開啟事務,可以通過transcational注解控制 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer" ref="stringSerializer" />
<property name="enableTransactionSupport" value="true" />
</bean>

對於hibernate的配置可知,第一個poolconfig是對連接池的配置。包括最大連接數,隊列數,存活時間,最大等待時間等等,還有一些額外的配置,請直接點擊JedisPoolConfig類源碼,進行查看。

這些配置的意思如果不明白的話,一定要去把線程池好好學習下。

第一個配置是連接工廠,顧名思義,最基本的使用一定是對連接的打開和關閉。我們需要為其配置redis服務器的賬戶密碼,端口號。(這裡還可以配置數據庫的index,但是我使用時候一直使用redis的默認數據庫,也就是第0個)

最後一個配置特別重要。這個類似於spring提供的HibernateDaoSupport。

接下來,全部講解都將圍繞這個類展開。

3. RedisTemplate的使用

這個類作為一個模版類,提供了很多快速使用redis的api,而不需要自己來維護連接,事務。

最初的時候,我創建的BaseRedisDao是繼承自這個類的。繼承的好處是我的每個Dao中,都可以自由的控制序列化器,自由的控制自己是否需要事務,這個先不需要了解,跟著我目前的這種配置方法來即可。

template提供了一系列的operation,比如valueOperation,HashOperation,ListOperation,SetOperation等,用來操作不同數據類型的Redis。

並且,RedisTemplate還提供了對應的*OperationsEditor,用來通過RedisTemplate直接注入對應的Operation。我們暫時不講這個。

對於下面的test1方法,我們暫時不用考慮,先了解通過RedisTemplate來使用connection操作Redis。

Test代碼如下:

package cn.test.spjedis;


import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cn.redis2.dao.IncrDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestRedis {
@Resource(name = "redisTemplate")
private RedisTemplate<String, String> template; // inject the template as ListOperations
//至於這個為什麼可以注入。需要參考AbstractBeanFactory doGetBean
//super.setValue(((RedisOperations) value).opsForValue());就這一行代碼 依靠一個editor
@Resource(name = "redisTemplate")
private ValueOperations<String, Object> vOps;

public void testSet(){
template.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
byte [] key = "tempkey".getBytes();
byte[] value = "tempvalue".getBytes();
connection.set(key, value);
return true;
}
});
}

public void testSet1(){
vOps.set("tempkey", "tempvalue");
}

@Autowired
private IncrDao incr;


@Test
public void addLink() {
System.out.println(incr.incr(13));
System.out.println(incr.get(13));
}

}

這個是對String類型插入的兩個測試。test方法中,使用了模版類提交回調(RedisCallBack)的方法來使用jedis connection操作數據。這一部分,有沒有似曾相識呢?

HibernateTemplate的HibernateCallback,以及Hibernate Session類中的doWork以及doReturningWork方法,都是使用了這樣的機制,方便對於連接或者session的統一管理。

public int excuteHqlUpdate(final String hql,final Object ...params){
return getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {
@Override
@SuppressWarnings("unchecked")
public Integer doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
queryObject.setParameter(i, params[i]);
}
}
return queryObject.executeUpdate();
}
});
}

4. 總結

我們這節,講了spring redis的配置使用,基本特性,以及引入使用RedisTemplate。通過之前HibernateTemplate的對比,也應該對RedisTemplate的基本設計有了一定的了解。下節,我們將進行深入學習RedisTempalte。

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2015-07/119792p2.htm

Copyright © Linux教程網 All Rights Reserved