SpringBoot2.X整合Redis

SpringBoot2.X整合Redis(集萬篇之總結(jié))

在學(xué)習(xí)過程當(dāng)中偶然遇到了redis,深深感受到他的強(qiáng)大之處。本篇博客就SpringBoot整合redis,
springboot1.X與2.X整合方式略有不同,本篇著重介紹2.X整合方法;

GitHub地址:

https://github.com/Guoxxin/springbootRedis.git

環(huán)境配置:

  1. Springboot 2.0.6
  2. redis 3.2.100
    鏈接:https://pan.baidu.com/s/1rbZkjd8vtlm9-IHnIbhX8g
    提取碼:wuly
  3. redis可視化工具
    鏈接:https://pan.baidu.com/s/1RKEkbs2qKQZ3PyABHaPTVQ
    提取碼:20f4

項(xiàng)目結(jié)構(gòu)圖:

item.png

代碼實(shí)現(xiàn):

  1. pom.xml引入依賴
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

2.yml文件配置

spring:

  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 3600ms #超時(shí)時(shí)間
    jedis:
      pool:
        max-active: 8 #最大連接數(shù)
        max-idle: 8 #最大空閑連接 默認(rèn)8
        max-wait: -1ms #默認(rèn)-1 最大連接阻塞等待時(shí)間
        min-idle: 0 #最小空閑連接

  1. 增加redis配置類 RedisConfig.java
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置連接工廠
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認(rèn)使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會(huì)跑出異常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 設(shè)置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 生成一個(gè)默認(rèn)配置,通過config對(duì)象即可對(duì)緩存進(jìn)行自定義配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.entryTtl(Duration.ofMinutes(1))     // 設(shè)置緩存的默認(rèn)過期時(shí)間,也是使用Duration設(shè)置
                .disableCachingNullValues();     // 不緩存空值
        // 設(shè)置一個(gè)初始化的緩存空間set集合
        Set<String> cacheNames =  new HashSet<>();
        cacheNames.add("timeGroup");
        cacheNames.add("user");
        // 對(duì)每個(gè)緩存空間應(yīng)用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("timeGroup", config);
        configMap.put("user", config.entryTtl(Duration.ofSeconds(120)));
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)// 使用自定義的緩存配置初始化一個(gè)cacheManager
                .initialCacheNames(cacheNames)  // 注意這兩句的調(diào)用順序,一定要先調(diào)用該方法設(shè)置初始化的緩存名,再初始化相關(guān)的配置
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }
}

4.redisTemplate具體使用方法

redisTemplate.opsForValue().set("你好啊","你好啊!!!");
效果1.png
ValueOperations vo = redisTemplate.opsForValue();
        vo.set("所有的博客",all);
效果二.png

查詢緩存中的 “所有的博客” 緩存

@RequestMapping("/getRedisBlog")
    public Result getredisBlog(){
        ValueOperations operations = redisTemplate.opsForValue();
        Object result = operations.get("所有的博客");
        return new Result(200,"獲取成功",result);
    }

效果3.png

ValueOperations接口說明

這個(gè)接口的實(shí)現(xiàn)類為DefaultValueOperations,default這個(gè)類同時(shí)繼承AbstractOperation,我們來看下這個(gè)類的構(gòu)造函數(shù):

DefaultValueOperations(RedisTemplate<K, V> template) {
super``(template);
}

這個(gè)類非公開的,需要傳入template來構(gòu)造。但是我們是無法訪問的。不過不要急,在RedisTemplate中,已經(jīng)提供了一個(gè)工廠方法:opsForValue()。這個(gè)方法會(huì)返回一個(gè)默認(rèn)的操作類。另外,我們可以直接通過ValueOperations operations = redisTemplate.opsForValue();來進(jìn)行注入。
opsForValue()集合使用說明
1). set(K key,V value)
新建緩存
redisTemplate.opsForValue().set("key","value");
2). get(Object key)
獲取緩存
edisTemplate.opsForValue().get("key");
具體可見 https://357029540.iteye.com/blog/2388965
講的特別詳細(xì)?。?!

如果本篇文章對(duì)您有幫助的話,贊一下莫不是對(duì)我最大的鼓勵(lì)!

致敬學(xué)習(xí)路上的你!

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

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

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