前言
本章基于上一章應用進行改造,增加redis
響應式與非響應式
SpringBoot2中已經(jīng)把redis的驅(qū)動從Jedis改為Lettuce,這也是實現(xiàn)響應式最關鍵的地方。
那什么是響應式呢?
簡單理解響應式
比如我們在使用excel時,單元格c1的值為2,單元格c2的值是3,單元格c3是一個公式(c1+c2)
如果改變c1或c2的值,c3單元格也會變更。這就是響應式。響應式在前端頁面應用非常廣泛。
1.引入需要的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
注意commons-pool2是必須要引用的。
2. 配置redis連接配置
spring.redis.host=192.168.222.12
spring.redis.password=123456
#連接池最小空閑連接,默認0
spring.redis.lettuce.pool.min-idle=5
#連接池最大空閑連接,默認8
spring.redis.lettuce.pool.max-idle=10
#連接池最大連接數(shù),負值表示沒有限制,默認8
spring.redis.lettuce.pool.max-active=20
#連接池最大等待時間,負值表示沒有限制,默認-1ms
spring.redis.lettuce.pool.max-wait=1000
3.使用樣例
@RestController
public class RedisController {
@Autowired
private ReactiveRedisTemplate reactiveRedisTemplate;
@Autowired
private ReactiveStringRedisTemplate stringRedisTemplate;
@RequestMapping("/redis/setData")
public String setData(){
Mono<Boolean> momo = reactiveRedisTemplate.opsForValue().set("test|string", "this is a string value");
momo.subscribe(System.out::println);
return "setData";
}
@RequestMapping("/redis/getData")
public Mono getData(){
Mono momo = reactiveRedisTemplate.opsForValue().get("test|string");
momo.subscribe(System.out::println);
return momo;
}
@RequestMapping("/redis/getData2")
public Mono getData2(){
Mono momo = reactiveRedisTemplate.opsForValue().get("test|string");
momo.subscribe(System.out::println);
return momo;
}
}
如果啟動正常,直接使用@Autowired即可。
另外要注意,不同的Template的序列化方案不同,比如樣例中,如果set使用的是ReactiveRedisTemplate,那用ReactiveStringRedisTemplate是get不到數(shù)據(jù)的。
這一點在做系統(tǒng)升級時一定要注意多測試。
結(jié)束語
本章主要實現(xiàn)接入數(shù)據(jù)庫。
如果對您有幫助,請給個贊。