spring boot Redis集成—RedisTemplate

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。

Spring boot 基于Spring, ?Redis集成與Spring大同小異。

文章示例代碼均以前篇筆記為基礎增加修改,直接上代碼:

pom.xml ?Redis相關依賴:

?

[html]?view plain?copy
  1. <?xml?version="1.0"?encoding="UTF-8"?>??
  2. <project?xmlns="http://maven.apache.org/POM/4.0.0"?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??
  3. ????xsi:schemaLocation="http://maven.apache.org/POM/4.0.0?http://maven.apache.org/xsd/maven-4.0.0.xsd">??
  4. ????<modelVersion>4.0.0</modelVersion>??
  5. ????<groupId>com.vic</groupId>??
  6. ????<artifactId>vic</artifactId>??
  7. ????<version>0.1.0</version>??
  8. ??
  9. ????<properties>??
  10. ????????<java.version>1.7</java.version>??
  11. ????</properties>??
  12. ??????
  13. ????<parent>??
  14. ????????<groupId>org.springframework.boot</groupId>??
  15. ????????<artifactId>spring-boot-starter-parent</artifactId>??
  16. ????????<version>1.3.8.RELEASE</version>??
  17. ????</parent>??
  18. ??
  19. ????<dependencies>??
  20. ????????<!--?spring?boot?-->??
  21. ????????<dependency>??
  22. ????????????<groupId>org.springframework.boot</groupId>??
  23. ????????????<artifactId>spring-boot-starter-web</artifactId>??
  24. ????????</dependency>??
  25. ??????????
  26. ????????<!--?mybatis?-->??
  27. ????????<dependency>??
  28. ????????????<groupId>org.springframework.boot</groupId>??
  29. ????????????<artifactId>spring-boot-starter-jdbc</artifactId>??
  30. ????????</dependency>??
  31. ??
  32. ????????<dependency>??
  33. ????????????<groupId>org.mybatis</groupId>??
  34. ????????????<artifactId>mybatis-spring</artifactId>??
  35. ????????????<version>1.2.2</version>??
  36. ????????</dependency>??
  37. ????????<dependency>??
  38. ????????????<groupId>org.mybatis</groupId>??
  39. ????????????<artifactId>mybatis</artifactId>??
  40. ????????????<version>3.2.8</version>??
  41. ????????</dependency>??
  42. ??
  43. ????????<dependency>??
  44. ????????????<groupId>mysql</groupId>??
  45. ????????????<artifactId>mysql-connector-java</artifactId>??
  46. ????????</dependency>??
  47. ??
  48. ????????<dependency>??
  49. ????????????<groupId>com.mchange</groupId>??
  50. ????????????<artifactId>c3p0</artifactId>??
  51. ????????????<version>0.9.2.1</version>??
  52. ????????</dependency>??
  53. ??????????
  54. ??????????
  55. ????????<!--?redis?-->??
  56. ????????<dependency>??
  57. ????????????<groupId>org.springframework.boot</groupId>??
  58. ????????????<artifactId>spring-boot-starter-redis</artifactId>??
  59. ??
  60. ????????</dependency>??
  61. ??????????
  62. ????????<!--Gson-->????
  63. ????????<dependency>????
  64. ????????????<groupId>com.google.code.gson</groupId>????
  65. ????????????<artifactId>gson</artifactId>????
  66. ????????</dependency>????
  67. ??????????
  68. ??????????
  69. ????</dependencies>??
  70. ????<build>??
  71. ????????<plugins>??
  72. ????????????<plugin>??
  73. ????????????????<groupId>org.springframework.boot</groupId>??
  74. ????????????????<artifactId>spring-boot-maven-plugin</artifactId>??
  75. ????????????</plugin>??
  76. ????????</plugins>??
  77. ????</build>??
  78. </project>??

?

?

application.properties增加redis相關屬性:

?

?

[plain]?view plain?copy
  1. #datasource??
  2. spring.datasource.jdbcUrl=jdbc:mysql://115.28.92.178:3306/wms?useUnicode\=true&characterEncoding\=utf8;autoReconnect\=true;maxReconnects\=10;connectTimeout\=180000;socketTimeout\=180000??
  3. spring.datasource.user=root??
  4. spring.datasource.password=xx??
  5. spring.datasource.driverClass=com.mysql.jdbc.Driver??
  6. spring.datasource.maxActive=100??
  7. spring.datasource.initialPoolSize=5??
  8. spring.datasource.minPoolSize=5??
  9. spring.datasource.maxPoolSize=20??
  10. spring.datasource.maxStatements=100??
  11. spring.datasource.maxIdleTime=3600??
  12. spring.datasource.acquireIncrement=2??
  13. spring.datasource.acquireRetryAttempts=10??
  14. spring.datasource.acquireRetryDelay=600??
  15. spring.datasource.testConnectionOnCheckin=true??
  16. spring.datasource.idleConnectionTestPeriod=1200??
  17. spring.datasource.checkoutTimeout=100000??
  18. ??
  19. ??
  20. #redis??
  21. spring.redis.hostName=115.28.92.178??
  22. spring.redis.port=6379????
  23. spring.redis.password=xxx??
  24. spring.redis.pool.maxActive=8????
  25. spring.redis.pool.maxWait=-1????
  26. spring.redis.pool.maxIdle=8????
  27. spring.redis.pool.minIdle=0????
  28. spring.redis.timeout=0??

?

?

com.vic.config包中新增RedisConfig.java:

?

?

[java]?view plain?copy
  1. /**?
  2. ?*??
  3. ?*?@author?vic?
  4. ?*?@desc?redis?config?bean?
  5. ?*?
  6. ?*/??
  7. @Configuration??
  8. @EnableAutoConfiguration??
  9. public?class?RedisConfig?{??
  10. ??
  11. ????private?static?Logger?logger?=?Logger.getLogger(RedisConfig.class);??
  12. ??????
  13. ????@Bean??
  14. ????@ConfigurationProperties(prefix="spring.redis")??
  15. ????public?JedisPoolConfig?getRedisConfig(){??
  16. ????????JedisPoolConfig?config?=?new?JedisPoolConfig();??
  17. ????????return?config;??
  18. ????}??
  19. ??????
  20. ????@Bean??
  21. ????@ConfigurationProperties(prefix="spring.redis")??
  22. ????public?JedisConnectionFactory?getConnectionFactory(){??
  23. ????????JedisConnectionFactory?factory?=?new?JedisConnectionFactory();??
  24. ????????JedisPoolConfig?config?=?getRedisConfig();??
  25. ????????factory.setPoolConfig(config);??
  26. ????????logger.info("JedisConnectionFactory?bean?init?success.");??
  27. ????????return?factory;??
  28. ????}??
  29. ??????
  30. ??????
  31. ????@Bean??
  32. ????public?RedisTemplate<?,??>?getRedisTemplate(){??
  33. ????????RedisTemplate<?,?>?template?=?new?StringRedisTemplate(getConnectionFactory());??
  34. ????????return?template;??
  35. ????}??
  36. }??

?

?

?

?

?

OK,此時Reddis已經集成完成,下面來對常用操作做一些封裝測試:

新增IRedisService接口定義一些常用操作接口,以及添加實現類RedisServiceImpl,代碼如下:

?

IRedisService.java

?

[java]?view plain?copy
  1. /**?
  2. ?*??
  3. ?*?@author?vic?
  4. ?*?@desc?redis?service?
  5. ?*/??
  6. public?interface?IRedisService?{??
  7. ??????
  8. ????public?boolean?set(String?key,?String?value);??
  9. ??????
  10. ????public?String?get(String?key);??
  11. ??????
  12. ????public?boolean?expire(String?key,long?expire);??
  13. ??????
  14. ????public?<T>?boolean?setList(String?key?,List<T>?list);??
  15. ??????
  16. ????public?<T>?List<T>?getList(String?key,Class<T>?clz);??
  17. ??????
  18. ????public?long?lpush(String?key,Object?obj);??
  19. ??????
  20. ????public?long?rpush(String?key,Object?obj);??
  21. ??????
  22. ????public?String?lpop(String?key);??
  23. ??????
  24. }??


RedisServiceImpl.java

?

?

[java]?view plain?copy
  1. /**?
  2. ?*??
  3. ?*?@author?vic?
  4. ?*?@desc?resdis?service?
  5. ?*?
  6. ?*/??
  7. @Service??
  8. public?class?RedisServiceImpl?implements?IRedisService{??
  9. ??
  10. ????@Autowired??
  11. ????private?RedisTemplate<String,??>?redisTemplate;??
  12. ??????
  13. ????@Override??
  14. ????public?boolean?set(final?String?key,?final?String?value)?{??
  15. ????????boolean?result?=?redisTemplate.execute(new?RedisCallback<Boolean>()?{??
  16. ????????????@Override??
  17. ????????????public?Boolean?doInRedis(RedisConnection?connection)?throws?DataAccessException?{??
  18. ????????????????RedisSerializer<String>?serializer?=?redisTemplate.getStringSerializer();??
  19. ????????????????connection.set(serializer.serialize(key),?serializer.serialize(value));??
  20. ????????????????return?true;??
  21. ????????????}??
  22. ????????});??
  23. ????????return?result;??
  24. ????}??
  25. ??
  26. ????public?String?get(final?String?key){??
  27. ????????String?result?=?redisTemplate.execute(new?RedisCallback<String>()?{??
  28. ????????????@Override??
  29. ????????????public?String?doInRedis(RedisConnection?connection)?throws?DataAccessException?{??
  30. ????????????????RedisSerializer<String>?serializer?=?redisTemplate.getStringSerializer();??
  31. ????????????????byte[]?value?=??connection.get(serializer.serialize(key));??
  32. ????????????????return?serializer.deserialize(value);??
  33. ????????????}??
  34. ????????});??
  35. ????????return?result;??
  36. ????}??
  37. ??
  38. ????@Override??
  39. ????public?boolean?expire(final?String?key,?long?expire)?{??
  40. ????????return?redisTemplate.expire(key,?expire,?TimeUnit.SECONDS);??
  41. ????}??
  42. ??
  43. ????@Override??
  44. ????public?<T>?boolean?setList(String?key,?List<T>?list)?{??
  45. ????????String?value?=?JSONUtil.toJson(list);??
  46. ????????return?set(key,value);??
  47. ????}??
  48. ??
  49. ????@Override??
  50. ????public?<T>?List<T>?getList(String?key,Class<T>?clz)?{??
  51. ????????String?json?=?get(key);??
  52. ????????if(json!=null){??
  53. ????????????List<T>?list?=?JSONUtil.toList(json,?clz);??
  54. ????????????return?list;??
  55. ????????}??
  56. ????????return?null;??
  57. ????}??
  58. ??
  59. ????@Override??
  60. ????public?long?lpush(final?String?key,?Object?obj)?{??
  61. ????????final?String?value?=?JSONUtil.toJson(obj);??
  62. ????????long?result?=?redisTemplate.execute(new?RedisCallback<Long>()?{??
  63. ????????????@Override??
  64. ????????????public?Long?doInRedis(RedisConnection?connection)?throws?DataAccessException?{??
  65. ????????????????RedisSerializer<String>?serializer?=?redisTemplate.getStringSerializer();??
  66. ????????????????long?count?=?connection.lPush(serializer.serialize(key),?serializer.serialize(value));??
  67. ????????????????return?count;??
  68. ????????????}??
  69. ????????});??
  70. ????????return?result;??
  71. ????}??
  72. ??
  73. ????@Override??
  74. ????public?long?rpush(final?String?key,?Object?obj)?{??
  75. ????????final?String?value?=?JSONUtil.toJson(obj);??
  76. ????????long?result?=?redisTemplate.execute(new?RedisCallback<Long>()?{??
  77. ????????????@Override??
  78. ????????????public?Long?doInRedis(RedisConnection?connection)?throws?DataAccessException?{??
  79. ????????????????RedisSerializer<String>?serializer?=?redisTemplate.getStringSerializer();??
  80. ????????????????long?count?=?connection.rPush(serializer.serialize(key),?serializer.serialize(value));??
  81. ????????????????return?count;??
  82. ????????????}??
  83. ????????});??
  84. ????????return?result;??
  85. ????}??
  86. ??
  87. ????@Override??
  88. ????public?String?lpop(final?String?key)?{??
  89. ????????String?result?=?redisTemplate.execute(new?RedisCallback<String>()?{??
  90. ????????????@Override??
  91. ????????????public?String?doInRedis(RedisConnection?connection)?throws?DataAccessException?{??
  92. ????????????????RedisSerializer<String>?serializer?=?redisTemplate.getStringSerializer();??
  93. ????????????????byte[]?res?=??connection.lPop(serializer.serialize(key));??
  94. ????????????????return?serializer.deserialize(res);??
  95. ????????????}??
  96. ????????});??
  97. ????????return?result;??
  98. ????}??
  99. ??
  100. }??


其中的JSONUtil類,可下載demo代碼查看,其實就是一個JSON的工具類。

?

?

在ExampleController中添加測試方法:

?

[java]?view plain?copy
  1. @RestController??
  2. public?class?ExampleController?{??
  3. ??
  4. ????@Autowired??
  5. ????private?IUserService?userService;??
  6. ??????
  7. ????@Autowired??
  8. ????private?IRedisService?redisService;??
  9. ??????
  10. ????@RequestMapping("/users")??
  11. ????public?ResponseModal?users(){??
  12. ????????List<User>?users?=?userService.getAll();??
  13. ????????ResponseModal?modal?=?new?ResponseModal(200,true,"",users);??
  14. ????????return?modal;??
  15. ????}??
  16. ??????
  17. ????@RequestMapping("/redis/set")??
  18. ????public?ResponseModal?redisSet(@RequestParam("value")String?value){??
  19. ????????boolean?isOk?=?redisService.set("name",?value);??
  20. ????????return?new?ResponseModal(isOk???200?:?500,?isOk,?isOk???"success"?:?"error"?,?null);??
  21. ????}??
  22. ??????
  23. ????@RequestMapping("/redis/get")??
  24. ????public?ResponseModal?redisGet(){??
  25. ????????String?name?=?redisService.get("name");??
  26. ????????return?new?ResponseModal(200,?true,"success",name);??
  27. ????}??
  28. ??????
  29. }??

?

?

?

?

?

運行Application的main函數

瀏覽器輸入:http://localhost:8080/redis/set?value=vic ?響應結果:

?

{"code":200,"success":true,"message":"success","response":null}

?

瀏覽器輸入:http://localhost:8080/redis/get ?響應結果:

?

{"code":200,"success":true,"message":"success","response":"vic"}

?

示例代碼下載

?

原文見:http://blog.csdn.net/i_vic/article/details/53081241

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

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

相關文章

QtCreator無法編輯源文件

在Qt Creator中新建工程&#xff0c;添加現有C源文件&#xff0c;有的源文件可以編輯&#xff0c;有的源文件編輯不了&#xff0c;發現無法編輯的源文件有一個共同特點&#xff0c;即其中都包含中文&#xff0c;且中文出現亂碼&#xff0c;于是&#xff0c;點擊Qt Creator菜單欄…

Unicode簡介和使用

一、Unicode簡介 在第一章中&#xff0c;我已經預告&#xff0c;C語言中在Microsoft Windows程序設計中扮演著重要角色的任何部分都會講述到&#xff0c;您也許在傳統文字模式程序設計中還尚未遇到過這些問題。寬字符集和Unicode差不多就是這樣的問題。 簡單地說&#xff0c;…

webpack4.x 模塊化淺析-CommonJS

先看下webpack官方文檔中對模塊的描述&#xff1a; 在模塊化編程中&#xff0c;開發者將程序分解成離散功能塊(discrete chunks of functionality)&#xff0c;并稱之為模塊。每個模塊具有比完整程序更小的接觸面&#xff0c;使得校驗、調試、測試輕而易舉。 精心編寫的模塊提供…

設計模式--抽象工廠(個人筆記)

一、抽象工廠的應用場景以及優缺點 1 應用場景&#xff1a; 如果系統需要多套的代碼解決方案&#xff0c;并且每套的代碼解決方案中又有很多相互關聯的產品類型&#xff0c;并且在系統中我們可以相互替換的使用一套產品的時候可以使用該模式&#xff0c;客戶端不需要依賴具體的…

利用阿里云OSS對文件進行存儲,上傳等操作

--pom.xml加入阿里OSS存儲依賴 <!--阿里云OSS存儲--> <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version> </dependency> --配置阿里云oss相關常量參數 /…

Java并發編程之ThreadGroup

ThreadGroup是Java提供的一種對線程進行分組管理的手段&#xff0c;可以對所有線程以組為單位進行操作&#xff0c;如設置優先級、守護線程等。 線程組也有父子的概念&#xff0c;如下圖&#xff1a; 線程組的創建 1 public class ThreadGroupCreator {2 3 public static v…

springboot 緩存ehcache的簡單使用

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 步驟&#xff1a; 1. pom文件中加 maven jar包&#xff1a; <!-- ehcache 緩存 --><dependency><groupId>net.sf.eh…

Spring boot + mybatis plus 快速構建項目,生成基本業務操作代碼。

---進行業務建表&#xff0c;這邊根據個人業務分析&#xff0c;不具體操作 --加入mybatis plus pom依賴 <!-- mybatis-plus 3.0.5--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId>&l…

給手機瀏覽器減負 輕裝上陣才能速度制勝

隨著手機瀏覽器的發展&#xff0c;瀏覽器已經變得臃腫不堪&#xff0c;各種“功能”系于一身&#xff0c;有廣告、社區、樂園等等&#xff0c;我們真的需要它們嗎&#xff1f;如何才能讓瀏覽器做到輕裝上陣&#xff0c;又能高效滿足我們需求呢&#xff1f; 過多“功能”的瀏覽器…

653. Two Sum IV - Input is a BST

題目來源&#xff1a; 自我感覺難度/真實難度&#xff1a; 題意&#xff1a; 分析&#xff1a; 自己的代碼&#xff1a; class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""Allself.InO…

解決 dubbo問題:Forbid consumer 192.xx.xx.1 access service com.xx.xx.xx.rpc.api.xx from registry 116.xx1

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 我的情況是&#xff1a; 原本我把服務放在A工程中&#xff0c;后來改到B工程中了&#xff0c;所以原來的服務不存在了&#xff0c;查不…

vue學習:7、路由跳轉

2019獨角獸企業重金招聘Python工程師標準>>> <body><div id"app"></div></body><script type"text/javascript">var Login {template: <div>我是登陸界面</div>};var Register {template: <div…

Spring Retry 重試機制實現及原理

概要 Spring實現了一套重試機制&#xff0c;功能簡單實用。Spring Retry是從Spring Batch獨立出來的一個功能&#xff0c;已經廣泛應用于Spring Batch,Spring Integration, Spring for Apache Hadoop等Spring項目。本文將講述如何使用Spring Retry及其實現原理。 背景 重試&…

inline 內聯函數詳解 內聯函數與宏定義的區別

一、在C&C中   一、inline 關鍵字用來定義一個類的內聯函數&#xff0c;引入它的主要原因是用它替代C中表達式形式的宏定義。表達式形式的宏定義一例&#xff1a;#define ExpressionName(Var1,Var2) ((Var1)(Var2))*((Var1)-(Var2))為什么要取代這種形式呢&#xff0c;且…

Oracle序列更新為主鍵最大值

我們在使用 Oracle 數據庫的時候&#xff0c;有時候會選擇使用自增序列作為主鍵。但是在開發過程中往往會遇到一些不規范的操作&#xff0c;導致表的主鍵值不是使用序列插入的。這樣在數據移植的時候就會出現各種各樣的問題。當然數據庫主鍵不使用序列是一種很好的方式&#xf…

dubbo forbid service的解決辦法

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 017-05-31 10:36:54.523 [http-nio-8080-exec-5] ERROR c.h.pdl.web.APIExceptionHandler - Unknown Exception, URI /payday-loan-co…

用SSH登錄遠程的機器,在遠程機器上執行本地機器上的腳本

假設本地的機器IP為10.245.111.90&#xff0c;我們想要在10.245.111.93上執行一個保存在10.245.111.90上的腳本。經過測試通過的命令如下&#xff1a;ssh root10.245.111.93 bash -s < /root/testlocal.sh如果要帶參數的話&#xff0c;那就需要參考這篇文章中描述的代碼了。…

golang學習之旅(1)

這段時間我開始了golang語言學習&#xff0c;其實也是為了個人的職業發展的拓展和衍生&#xff0c;語言只是工具&#xff0c;但是每個語言由于各自的特點和優勢&#xff0c;golang對于當前編程語言的環境&#xff0c;是相對比較新的語言&#xff0c;對于區塊鏈&#xff0c;大數…

為什么要在Linux平臺上學C語言?用Windows學C語言不好嗎?

用Windows還真的是學不好C語言。C語言是一種面向底層的編程語言&#xff0c;要寫好C程序&#xff0c;必須對操作系統的工作原理非常清楚&#xff0c;因為操作系統也是用C寫的&#xff0c;我們用C寫應用程序直接使用操作系統提供的接口&#xff0c;Linux是一種開源的操作系統&am…

數據庫中Schema(模式)概念的理解

在學習SQL的過程中&#xff0c;會遇到一個讓你迷糊的Schema的概念。實際上&#xff0c;schema就是數據庫對象的集合&#xff0c;這個集合包含了各種對象如&#xff1a;表、視圖、存儲過程、索引等。為了區分不同的集合&#xff0c;就需要給不同的集合起不同的名字&#xff0c;默…