Spring Data Redis實戰之提供RedisTemplate

為什么80%的碼農都做不了架構師?>>> ??hot3.png

參考:

http://www.cnblogs.com/edwinchen/p/3816938.html

本項目創建的是Maven項目

一、pom.xml引入dependencies

        <dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.7.3.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.7.3</version><exclusions><exclusion><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version></dependency>

二、配置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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxTotal" value="${redis.pool.maxTotal}" /><property name="maxIdle" value="${redis.pool.maxIdle}" /><property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" /><property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /><property name="testOnReturn" value="${redis.pool.testOnReturn}" /><property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/></bean><bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.password}"p:poolConfig-ref="poolConfig"/><bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"><property name="connectionFactory" ref="connectionFactory" /><property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /></property><property name="valueSerializer"><bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /></property></bean></beans>

注意:配置poolConfig中property 的name 需要對應JedisPoolConfig這個類中實際的屬性;

配置connectionFactory同樣要注意這個,因為其他博文配置屬性時有所不同,主要是因為redis版本不同引起的有所不同。

三、properties文件配置值

# poolConfig 配置信息
redis.pool.maxTotal=1024
redis.pool.maxIdle=200
redis.pool.maxWaitMillis=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.pool.testWhileIdle=true# connectionFactory 配置信息
redis.host=localhost
redis.port=6379
redis.timeout=15000
redis.password=123456

另外,需要注意的是,要引入該文件可以在applicationContext-redis.xml加入

<!-- scanner redis properties 假如有封裝用于加載properties,就不需要加這句了 -->
<context:property-placeholder location="classpath:property/redis.properties" />

四、使用RedisTemplate

其他項目需要RedisTemplate的時候,需要引入以上maven模塊的dependency

測試類使用:

/*** 測試 spring-data-redis 集成* Created by zhile on 2017/5/12 0012.*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void testTemple() {ValueOperations valueOperations = redisTemplate.opsForValue();valueOperations.set("spring-data-redis::test", "tom", 1000, TimeUnit.SECONDS);System.out.println("set successed");
/*ValueOperations valueOpers = redisTemplate.opsForValue();System.out.println("get:" + valueOpers.get("spring-data-redis::test"));*/}@Testpublic void testRedisTemple() {ValueOperations valueOpers = redisTemplate.opsForValue();System.out.println("get:" + valueOpers.get("spring-data-redis::test"));}
}

這樣,只要引入集成了RedisTemplate的maven模塊,就可以直接使用。

?

五、問題小結:

1.引入的dependency需要注意兼容性,因為redis2.7.3 中的commons-pool2版本不完整,需要引入較新的commons-pool2。

Caused by: java.lang.NoSuchMethodError: 
redis.clients.jedis.JedisPool.apache/commons/pool2/impl/GenericObjectPoolConfig等等

2.假如spring-data-redis的版本1.8.3,而redis的版本還是為2.7.3的話,會報這樣的錯:

所以,需要注意版本兼容的問題,這是因為spring-data-redis的版本太新點。

java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'redisTemplate' defined in class path resource [applicationContext-redis.xml]:...Caused by: org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'connectionFactory' defined in class path resource[applicationContext-redis.xml]:...Caused by: java.lang.NoClassDefFoundError:
Could not initialize class org.springframework.data.redis.connection.jedis.JedisConnectionFactory...

?

補充參考:

http://zhaozhiming.github.io/blog/2015/04/12/spring-data-redis/

http://www.baeldung.com/spring-data-redis-tutorial

轉載于:https://my.oschina.net/itommy/blog/898416

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/541393.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541393.shtml
英文地址,請注明出處:http://en.pswp.cn/news/541393.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java BigInteger類| and()方法與示例

BigInteger類和()方法 (BigInteger Class and() method) and() method is available in java.math package. and()方法在java.math包中可用。 and() method is used to perform and operation between this BigInteger and the given BigInteger (val) [i.e. (this BigInteger)…

php映射,PHP實現路由映射到指定控制器

自定義路由的功能&#xff0c;指定到pathinfo的url上,再次升級之前的腳本SimpleLoader.phpclass SimpleLoader{public static function run($rulesarray()){header("content-type:text/html;charsetutf-8");self::register();self::commandLine();self::router($rule…

stl vector 函數_vector :: clear()函數,以及C ++ STL中的示例

stl vector 函數C vector :: clear()函數 (C vector::clear() function) vector::clear() is a library function of "vector" header, it is used to remove/clear all elements of the vector, it makes the 0 sized vector after removing all elements. vector …

Commonjs規范及Node模塊實現

前面的話 Node在實現中并非完全按照CommonJS規范實現&#xff0c;而是對模塊規范進行了一定的取舍&#xff0c;同時也增加了少許自身需要的特性。本文將詳細介紹NodeJS的模塊實現 引入 nodejs是區別于javascript的&#xff0c;在javascript中的頂層對象是window&#xff0c;而在…

thinkphp3 php jwt,ThinkPHP5 使用 JWT 進行加密

- 使用 Composer安裝此擴展- 代碼示例<?php /*** [InterCommon-接口公用]* Author RainCyan* DateTime 2019-08-12T16:38:080800*/namespace app\hladmin\controller;use think\Controller;use \Firebase\JWT\JWT;class InterCommonController extends Controller {private…

數據管理與商業智能_商業智能與數據科學

數據管理與商業智能In this heavily jargonized trade, the words typically overlap one another, leading to a scarcity of understanding or a state of confusion around these ideas. whereas big data vs analytics or computing vs machine learning vs cognitive inte…

JavaWeb網上圖書商城完整項目--day02-14.登錄功能的login頁面處理

1、現在注冊成功之后&#xff0c;我們來到登錄頁面&#xff0c;登錄頁面在于 在登錄頁面。我們也需要向注冊頁面一樣對登錄的用戶名、密碼 驗證碼等在jsp頁面中進行校驗&#xff0c;校驗我們單獨放置一個login.js文件中進行處理&#xff0c;然后login.jsp加載該js文件 我們來看…

php多線程是什么意思,多線程是什么意思

線程是操作系統能夠進行運算調度的最小單位&#xff0c;它被包含在進程之中&#xff0c;是進程中的實際運作單位&#xff0c;而多線程就是指從軟件或者硬件上實現多個線程并發執行的技術&#xff0c;具有多線程能力的計算機因有硬件支持而能夠在同一時間執行多于一個線程&#…

c++一個類創建多個對象_C ++ | 創建一個類的多個對象

c一個類創建多個對象In the below program, we are creating a C program to create multiple objects of a class. 在下面的程序中&#xff0c;我們正在創建一個C 程序來創建一個類的多個對象 。 /* C program to create multiple objects of a class */#include <iostrea…

Activity中與ListActivity中使用listview區別

一.Activity中與ListActivity中使用listview區別&#xff08;本身沒多大區別&#xff0c;只是ListActivity在listview的顯示上做了一些優化&#xff09;Activity中使用Listview步驟&#xff1a;1.xml布局中,ListView標簽id可以任意取值如&#xff1a;<ListView andro…

java相關是什么,什么是java

java基礎常見面試題&#xff0c;這是一篇超長的隨筆&#xff01;&#xff01;&#xff01;1. Java基礎部分....................................................... 4 1、一個".java"源文件中是否可以包括多個類(不是內部類)&#xff1f;有什么限制&#xff1f;.. …

如何在Scala中將Double轉換為String?

Double in Scala is a data type that stores numerical values that have decimals. It can store a 64-bit floating point number. Scala中的Double是一種數據類型&#xff0c;用于存儲帶有小數的數值。 它可以存儲一個64位浮點數。 Example: 例&#xff1a; val decimal…

basic knowledge

Position 屬性&#xff1a;規定元素的定位類型。即元素脫離文檔流的布局&#xff0c;在頁面的任意位置顯示。 ①absolute &#xff1a;絕對定位&#xff1b;脫離文檔流的布局&#xff0c;遺留下來的空間由后面的元素填充。定位的起始位置為最近的父元素(postion不為static)&…

avatar.php uid,phpcms函數庫中獲取會員頭像方法get_memberavatar()有時無效問題

修復方法&#xff1a;首先我先給出無效情況的演示代碼&#xff0c;如下&#xff1a;$userid intval($_GET[userid]);$userinfo $this->db->get_one(userid.$userid);$this->db->set_model(10); //原因便在這里$userdetail $this->db->get_one("useri…

ruby 集合 分組_將Ruby中兩個集合的所有元素結合在一起

ruby 集合 分組In this program, we will see how we can combine the two sets? This is not a very difficult task. This can be easily done with the help of the operator. In many places of programming, you will find that operator is overloaded for various ty…

?Python中面向對象的編程

Python面向對象的編程1概述&#xff08;1&#xff09;面向對象編程面向對象的編程是利用“類”和“對象”來創建各種模型來實現對真實世界的描述&#xff0c;使用面向對象編程的原因一方面是因為它可以使程序的維護和擴展變得更簡單&#xff0c;并且可以大大提高程序開發效率&a…

php中用for循環制作矩形,PHP中for循環語句的幾種變型

PHP中for循環語句的幾種變型2021-01-22 10:21:42406for語句可以說是PHP(同時也是多種語言)的循環控制部份最基本的一個語句了&#xff0c;for語句的執行規律和基礎用法在這里就不多說&#xff0c;可以參見PHP手冊for語句部分。PHP手冊中對它的語法定義如下&#xff1a;for(expr…

c語言用命令行編譯運行程序_使用C程序執行系統命令

c語言用命令行編譯運行程序Sometimes, we may need to execute Linux/Windows DOS commands through our C program. (Note: the code given below is compiled and executed on Linux GCC compiler, so here we are testing Linux commands only). 有時&#xff0c;我們可能需…

python 熊貓,Python熊貓

我試圖連續分組和計算相同的信息&#xff1a;#Functionsdef postal_saude ():global df, lista_solic#List of solicitantes in Postal Saudelist_sol [lista_solic["name1"], lista_solic["name2"]]#filter Postal Saude Solicitantesdf df[(df[Cliente…

Spring的兩種任務調度Scheduled和Async

Spring提供了兩種后臺任務的方法,分別是: 調度任務&#xff0c;Schedule異步任務&#xff0c;Async當然&#xff0c;使用這兩個是有條件的&#xff0c;需要在spring應用的上下文中聲明<task:annotation-driven/>當然&#xff0c;如果我們是基于java配置的&#xff0c;需要…