Redis實(shí)戰(zhàn)(1)-SpringBoot2.0整合Redis自定義注入模板操作Bean組件

作者: 修羅debug
版權(quán)聲明:本文為博主原創(chuàng)文章,遵循 CC 4.0 by-sa 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接和本聲明。

摘要:對(duì)于Redis,相信很多小伙伴早已有所耳聞,更有甚者,已經(jīng)將其應(yīng)用到許許多多的項(xiàng)目當(dāng)中了!沒錯(cuò),它就是目前業(yè)界應(yīng)用相當(dāng)廣泛的其中一種緩存中間件,也可以算是其中的佼佼者吧,從本篇文章開始,我們將基于SpringBoot2.0整合搭建的微服務(wù)項(xiàng)目為奠基,開啟中間件Redis的實(shí)戰(zhàn)之路!

內(nèi)容:本篇文章我們將首先基于SpringBoot2.0搭建的項(xiàng)目整合緩存中間件Redis,在項(xiàng)目中加入跟Redis相關(guān)的、常見的配置信息,并自定義注入Redis的模板操作組件StringRedisTemplate和RedisTemplate,最終給大伙擼個(gè)簡單的Demo并由此開啟Redis的實(shí)戰(zhàn)之旅!

(1)第一步當(dāng)然是先加入中間件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常見的相關(guān)配置信息,包括host、port等基本信息,在這里我們提供了兩種配置方式,即“單機(jī)模式”和“集群模式”的配置,如下所示:  

#redis 單機(jī)配置
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

在該配置文件中,我們還加入了“鏈接池”的概念,其中,鏈接池里最小可用的鏈接數(shù)為100個(gè),最大可用的連接數(shù)為300個(gè),如果還不夠而需要?jiǎng)討B(tài)擴(kuò)增時(shí),我們將最終將活躍的鏈接數(shù)增加到500個(gè)?。ㄈ绻?00個(gè)還不夠,那就得堵塞等待了,等待期間,如果時(shí)間超過了默認(rèn)配置的超時(shí)時(shí)間,那將報(bào)出類似于connection reset或者connection error的錯(cuò)誤)

(2)接下來,我們將基于整合搭建好的項(xiàng)目自定義注入Redis的操作模板組件,即主要是StringRedisTemplate和RedisTemplate。

值得一提的是,在傳統(tǒng)的Java Web項(xiàng)目中,如Spring+SpringMVC+Mybatis整合的項(xiàng)目,一般是直接采用基于Jedis封裝出一個(gè)JedisUtil工具類,這種方式跟以前使用JDBCUtil操作DB數(shù)據(jù)庫時(shí)有點(diǎn)類似,其缺陷還是比較明顯的(如需要手動(dòng)創(chuàng)建鏈接、關(guān)閉鏈接資源等操作)

而SpringBoot的問世,帶來了“約定優(yōu)先于配置”、“起步依賴”等優(yōu)點(diǎn),省去了許多以往需要手動(dòng)創(chuàng)建、關(guān)閉鏈接等有可能消耗資源的操作,即直接就內(nèi)置在了SpringBoot Redis的起步依賴中了,而對(duì)于如何更加便捷的操作Redis,SpringBoot更是直接封裝、提供了兩大模板操作組件StringRedisTemplate和RedisTemplate,如下所示我們自定義注入了這兩個(gè)模板操作組件,即主要指定其序列化的相關(guān)策略:

/**
* @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);
//設(shè)置序列化策略
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)至此,我們已經(jīng)做好了相關(guān)的前奏準(zhǔn)備,接下來我們寫個(gè)簡單的Demo,意思意思一下“開啟Redis的實(shí)戰(zhàn)之路”:  

/**
* @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數(shù)據(jù)類型存儲(chǔ)特定的一串信息(在這里指的是一串字符串常量值,由前端傳遞過來!)

(4)最后,我們基于Postman進(jìn)行自測(學(xué)會(huì)自測是一個(gè)Java攻城獅必備的技能以及良好的習(xí)慣),兩張圖加以概括吧:



好了,本篇文章我們就介紹到這里了,建議各位小伙伴一定要照著文章提供的樣例代碼擼一擼,只有擼過才能知道這玩意是咋用的,否則就成了“空談?wù)摺?!?duì)Redis相關(guān)技術(shù)棧以及實(shí)際應(yīng)用場景實(shí)戰(zhàn)感興趣的小伙伴可以前往Debug搭建的技術(shù)社區(qū)的課程中心進(jìn)行學(xué)習(xí)觀看:https://www.fightjava.com/web/index/course/detail/12

其他相關(guān)的技術(shù),感興趣的小伙伴可以關(guān)注底部Debug的技術(shù)公眾號(hào),或者加Debug的微信,拉你進(jìn)“微信版”的真正技術(shù)交流群!一起學(xué)習(xí)、共同成長!

補(bǔ)充:

1、本文涉及到的相關(guān)的源代碼可以到此地址,check出來進(jìn)行查看學(xué)習(xí):

https://gitee.com/steadyjack/SpringBootRedis

2、目前Debug已將本文所涉及的內(nèi)容整理錄制成視頻教程,感興趣的小伙伴可以前往觀看學(xué)習(xí):https://www.fightjava.com/web/index/course/detail/12

3、關(guān)注一下Debug的技術(shù)微信公眾號(hào),最新的技術(shù)文章、課程以及技術(shù)專欄將會(huì)第一時(shí)間在公眾號(hào)發(fā)布哦!