概述:本系列博文所涉及的相關內容來源於debug親自錄製的實戰課程:緩存中間件Redis技術入門與應用場景實戰(SpringBoot2.x + 搶紅包系統設計與實戰),感興趣的小夥伴可以點擊自行前往學習(畢竟以視頻的形式來掌握技術 會更快!) ,文章所屬專欄:緩存中間件Redis技術入門與實戰
摘要:對於Redis,相信很多小夥伴早已有所耳聞,更有甚者,已經將其應用到許許多多的項目當中了!沒錯,它就是目前業界應用相當廣泛的其中一種緩存中間件,也可以算是其中的佼佼者吧,從本篇文章開始,我們將基於SpringBoot2.0整合搭建的微服務項目爲奠基,開啓中間件Redis的實戰之路!
內容:本篇文章我們將首先基於SpringBoot2.0搭建的項目整合緩存中間件Redis,在項目中加入跟Redis相關的、常見的配置信息,並自定義注入Redis的模板操作組件StringRedisTemplate和RedisTemplate,最終給大夥擼個簡單的Demo並由此開啓Redis的實戰之旅!
(1)第一步當然是先加入中間件Redis的依賴Jar,如下所示:
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.3.RELEASE</version> </dependency>
然後是在配置文件application.properties中加入Redis常見的相關配置信息,包括host、port等基本信息,在這裏我們提供了兩種配置方式,即“單機模式”和“集羣模式”的配置,如下所示:
#redis 單機配置 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.jedis.pool.min-idle=100 spring.redis.jedis.pool.max-idle=300 spring.redis.jedis.pool.max-active=500 #集羣配置 #spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382
在該配置文件中,我們還加入了“鏈接池”的概念,其中,鏈接池裏最小可用的鏈接數爲100個,最大可用的連接數爲300個,如果還不夠而需要動態擴增時,我們將最終將活躍的鏈接數增加到500個!(如果500個還不夠,那就得堵塞等待了,等待期間,如果時間超過了默認配置的超時時間,那將報出類似於connection reset或者connection error的錯誤)
(2)接下來,我們將基於整合搭建好的項目自定義注入Redis的操作模板組件,即主要是StringRedisTemplate和RedisTemplate。值得一提的是,在傳統的Java Web項目中,如Spring+SpringMVC+Mybatis整合的項目,一般是直接採用基於Jedis封裝出一個JedisUtil工具類,這種方式跟以前使用JDBCUtil操作DB數據庫時有點類似,其缺陷還是比較明顯的(如需要手動創建鏈接、關閉鏈接資源等操作)
而Spring Boot的問世,帶來了“約定優先於配置”、“起步依賴”等優點,省去了許多以往需要手動創建、關閉鏈接等有可能消耗資源的操作,即直接就內置在了Spring Boot Redis的起步依賴中了,而對於如何更加便捷的操作Redis,Spring Boot更是直接封裝、提供了兩大模板操作組件StringRedisTemplate和RedisTemplate,如下所示我們自定義注入了這兩個模板操作組件,即主要指定其序列化的相關策略:
/** * @EnableCaching:開啓緩存(註解生效的) * redis的操作組件自定義注入配置 * @Author:debug (SteadyJack) * @Link: wx-> debug0868 qq-> 1948831260 * @Date: 2019/10/29 16:59 **/ @Configuration @EnableCaching public class RedisConfig { @Autowired private RedisConnectionFactory connectionFactory; @Bean public RedisTemplate redisTemplate(){ RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); //設置序列化策略 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean public StringRedisTemplate stringRedisTemplate(){ StringRedisTemplate stringRedisTemplate=new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(connectionFactory); return stringRedisTemplate; } }
(3)至此,我們已經做好了相關的前奏準備,接下來我們寫個簡單的Demo,意思意思一下“開啓Redis的實戰之路”:
/** * @Author:debug (SteadyJack) * @Link: weixin-> debug0868 qq-> 1948831260 * @Date: 2019/10/29 15:47 **/ @RestController @RequestMapping("base") public class BaseController { private static final Logger log= LoggerFactory.getLogger(BaseController.class); @Autowired private StringRedisTemplate stringRedisTemplate; private static final String RedisHelloWorldKey="SpringBootRedis:HelloWorld"; @RequestMapping(value = "/hello/world/put",method = RequestMethod.POST) @ResponseBody public BaseResponse helloWorldPut(@RequestParam String helloName){ BaseResponse response=new BaseResponse(StatusCode.Success); try { stringRedisTemplate.opsForValue().set(RedisHelloWorldKey,helloName); response.setData("hello world!"); }catch (Exception e){ log.info("--hello world get異常信息: ",e.fillInStackTrace()); response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage()); } return response; } @RequestMapping(value = "/hello/world/get",method = RequestMethod.GET) @ResponseBody public BaseResponse helloWorldGet(){ BaseResponse response=new BaseResponse(StatusCode.Success); try { String result=stringRedisTemplate.opsForValue().get(RedisHelloWorldKey); response.setData(result); }catch (Exception e){ log.info("--hello world get異常信息: ",e.fillInStackTrace()); response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage()); } return response; } }
上述代碼就是簡單的基於Redis的String數據類型存儲特定的一串信息(在這裏指的是一串字符串常量值,由前端傳遞過來!)
(4)最後,我們基於Postman進行自測(學會自測是一個Java攻城獅必備的技能以及良好的習慣),兩張圖加以概括吧:
好了,本篇文章我們就介紹到這裏了,建議各位小夥伴一定要照着文章提供的樣例代碼擼一擼,只有擼過才能知道這玩意是咋用的,否則就成了“空談者”!對Redis相關技術棧以及實際應用場景實戰感興趣的小夥伴可以咱們51cto學院 debug親自錄製的課程進行學習:緩存中間件Redis技術入門與應用場景實戰(SpringBoot2.x + 搶紅包系統設計與實戰)
補充:
1、本文涉及到的相關的源代碼可以到此地址,check出來進行查看學習:https://gitee.com/steadyjack/SpringBootRedis
2、目前debug已將本文所涉及的內容整理錄製成視頻教程,感興趣的小夥伴可以前往觀看學習:https://edu.51cto.com/course/20384.html