Redis實戰(1):SpringBoot2.0整合Redis自定義注入操作Bean組件

對於Redis,相信很多小夥伴早已有所耳聞,更有甚者,已經將其應用到許許多多的項目當中了!沒錯,它就是目前業界應用相當廣泛的其中一種緩存中間件,也可以算是其中的佼佼者吧,從本篇文章開始,我們將基於SpringBoot2.0整合搭建的微服務項目為奠基,開啟中間件Redis的實戰

之路!

內容

本篇文章我們將首先基於SpringBoot2.0搭建的項目整合緩存中間件Redis,在項目中加入跟Redis相關的、常見的配置信息,並自定義注入Redis的模板操作組件StringRedisTemplate和RedisTemplate,最終給大夥擼個簡單的Demo並由此開啟Redis的實戰之旅!

(1)第一步當然是先加入中間件Redis的依賴Jar,如下所示:


<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數據庫時有點類似,其缺陷還是比較明顯的(如需要手動創建鏈接、關閉鏈接資源等操作)

而SpringBoot的問世,帶來了"約定優先於配置"、"起步依賴"等優點,省去了許多以往需要手動創建、關閉鏈接等有可能消耗資源的操作,即直接就內置在了SpringBoot Redis的起步依賴中了,而對於如何更加便捷的操作Redis,SpringBoot更是直接封裝、提供了兩大模板操作組件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> 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;
}
}/<string>

(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實戰(1):SpringBoot2.0整合Redis自定義注入操作Bean組件

Redis實戰(1):SpringBoot2.0整合Redis自定義注入操作Bean組件

好了,本篇文章我們就介紹到這裡了,建議各位小夥伴一定要照著文章提供的樣例代碼擼一擼,只有擼過才能知道這玩意是咋用的,否則就成了"空談者"!對Redis相關技術棧以及實際應用場景實戰感興趣的小夥伴可以前往[程序員實戰基地官網]課程中心進行學習觀看!


分享到:


相關文章: