SpringBoot項目實戰(zhàn)(二): redis

前言

本章基于上一章應用進行改造,增加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ù)庫。
如果對您有幫助,請給個贊。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容