spring-boot 利用autoconfiguration整合Redis

springboot整合redis有多種方式,可以自己通過JavaConfig的方式獲取RedisTemplate對象,也可以利用spring-boot-autoconfiguration.jar包中已有的RedisAutoConfiguration.class類來獲取RedisTemplate對象。本文介紹一個整合redis最簡單的方式。

spring-boot 自己編寫一個spring-boot-starter-redis文章的最后,我們簡單的拋磚引玉了一下,建議讀者先看這篇文章,了解原理。

打開spring-boot-autoconfiguration.jar下的RedisProperties.class,看看源碼。redis為我們提供了很多配置項,我們只需要在application.properties文件中為相應(yīng)的key賦值就好了,springboot還為我們支持了Cluster集群和Sentinel哨兵,功能很強(qiáng)大。

打開spring-boot-autoconfiguration.jar下的RedisAutoConfiguration.class,springboot為我們自動裝配了整合redis需要的用到的各種bean,我們只需要從spring容器中直接獲取就可以了。

好,接下來我們試試看

引入依賴

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

springboot1.4版本以前依賴為spring-boot-starter-redis,springboot1.4版本后依賴為spring-boot-starter-data-redis

配置application.properties

在application.properties中配置如下信息:相應(yīng)的key值在RedisProperties.class中有

#redis共有16個庫,分別為0-15
spring.redis.database=0
#redis所在ip地址
spring.redis.host=127.0.0.1
#連接redis的密碼
spring.redis.password=
#redis的端口號
spring.redis.port=6379
#redis連接池最大空閑連接
spring.redis.pool.maxIdle=10
#redis連接池最大連接數(shù)
spring.redis.pool.max-active=200
#redis連接池最大超時時間
spring.redis.pool.max-wait=3000

就這么簡單,springboot會幫我們把我們需要的bean放入容器中,我們只管獲取就行。有哪些bean,如何實現(xiàn)的,參照RedisAutoConfiguration.class源碼。

編寫啟動類,執(zhí)行

@SpringBootApplication
public class BlogApplication {
    public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(BlogApplication.class, args);
        //我們需要的就是StringRedisTemplate對象,也可以通過@Autowired注解獲取
        StringRedisTemplate stringRedisTemplate = context.getBean(StringRedisTemplate.class);

        //往redis中存入數(shù)據(jù)
        stringRedisTemplate.execute((RedisConnection connection) -> {
            RedisSerializer<String> serializer = stringRedisTemplate.getStringSerializer();
            connection.set(serializer.serialize("朱勇銘"), serializer.serialize("你好!"));
            return true;
        });

        //從redis中取出數(shù)據(jù)
        String result = stringRedisTemplate.execute((RedisConnection connection) -> {
            RedisSerializer<String> serializer = stringRedisTemplate.getStringSerializer();
            return serializer.deserialize(connection.get(serializer.serialize("朱勇銘")));
        });
        System.out.println(result);
    }
}
console result

以上就是本節(jié)的全部內(nèi)容,感興趣的讀者可以關(guān)注我的springboot系列其他文章哦~

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

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

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