SpringBoot日記——Redis整合

來源:互聯網
上載者:User

標籤:context   nbsp   問題   ima   manage   spring   圖片   dock   ctr   

  上一篇文章,簡單記錄了一下緩衝的使用方法,這篇文章將把我們熟悉的redis整合進來。

  那麼如何去整合呢?首先需要下載和安裝,為了使用方便,也可以做環境變數的配置。

  下載和安裝的方法,之前有介紹,在docker中的使用,這裡不做相關介紹,有想在windows環境下使用的,自己搜一下如何windows安裝使用redis吧~(看這裡也可以)

  正題:  SpringBoot對應(內建)RedisClient是不同的

  SpringBoot1.5.x版本 -> jedis 
  SpringBoot2.x版本 - > lettuce  (本文以2.x為例)

  Redis啟動與應用

  啟動redis服務,並開啟管理用戶端。其中預設的連接埠號碼,可以通過修改config來實現。

  按照的步驟,連結本地的redis,如果你是在遠程伺服器安裝的,ip記得填寫伺服器的。

  選中我們做好的連結,右鍵開啟console或者ctrl+T,開啟控制台,我們來測試一下命令是否可用~

  在控制台輸入命令,看一下(Redis命令點擊查看)

  繼續輸入命令,可以看到字串會相應的做拼接,這就是追加key值的命令的作用。其他命令,自己可以去試一下~

  

  整合到SpringBoot中

  接下來,我們將這個redis整合到SpringBoot中來,首先,在pom.xml中添加

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

  1.配置redis:到設定檔中添加:(如果是遠程伺服器,自己替換IP)

spring.redis.host=127.0.0.1

    添加好以後我們來測試一下,首先,為了存取資料到redis中,添加如下的代碼,我們接著看這兩個如何使用。

    @Autowired    StringRedisTemplate stringRedisTemplate;    // k-v都是字串    @Autowired    RedisTemplate redisTemplate;    // k-v都是對象

    先看字串的,跟之前在console中輸入命令一樣的作用,執行測試後,檢查下redis中,確實有產生的msg,說明我們的關聯和操作是成功的。

        stringRedisTemplate.opsForValue().append("msg", "Hello");  //append中添加的是兩個字串,也就是上邊的k-v字串操作

    所以,你該明白第二個k-v是對象的意思了吧?繼續測試方法中這樣寫:(我們將查詢的這個對象存到緩衝中)

        Employee empById = employeeMapper.getEmpById(1);        redisTemplate.opsForValue().set("emp-01", empById);

    來看結果:(Cannot serialize表示無法序列化,這裡先看下如何處理,稍後來說為什麼以及如何最佳化)

    我們將bean.Employee的類這樣寫,就可以保證基本的序列化: implements Serializable

public class Employee implements Serializable {xxxx}

    再次運行,查看結果:(運行成功了,可這一堆亂碼一樣的是什麼呢?)

      其實預設的序列化是JDK的,我們需要自己最佳化一下,比如編程json的序列化。

          來看如何最佳化呢,我們需要自己建立一個redis的配置,來序列化我們自己想要的json格式(其實就是把RedisAutoConfiguration中的方法拿出來稍微的修改一下)

          注意,我把主程式中的@EnableCaching,放到這裡了,主程式那裡就不用寫了?後邊我們再來實驗一下

import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.cache.RedisCacheWriter;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import java.time.Duration;@Configuration@EnableCachingpublic class MyRedisConfig {    @Bean    public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory) {        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()                .entryTtl(Duration.ofHours(1))  // 設定緩衝有效期間一小時                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(                        new GenericJackson2JsonRedisSerializer())); // 設定json格式序列化        return RedisCacheManager                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))                .cacheDefaults(redisCacheConfiguration).build();    }}

 

  然後使用我們自己建立的template方法,做一個測試,看下結果:(註解證明木有問題)

        Employee empById = employeeMapper.getEmpById(1);        employeeRedisTemplate.opsForValue().set("emp-01", empById);

  

  是不是看起來舒服多了。

  當然,如果我們針對不同的情況做不同的書寫有時候也是必要的,所以也可以這樣寫:(new那一行,看下變化,你就知道了~),但記住,如果你有多個個性配置的時候要加入註解@Primary,這個可以讓該bean作為預設的主緩衝管理器來使用,不然會報錯滴~

    @Bean    public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory) {        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()                .entryTtl(Duration.ofHours(1))  // 設定緩衝有效期間一小時                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(                        new Jackson2JsonRedisSerializer<Employee>(Employee.class))); // 設定json格式序列化        return RedisCacheManager                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))                .cacheDefaults(redisCacheConfiguration).build();    }

 

  如上,redis的簡單使用就說這些,後邊我可能還會把文章擴充一下,具體說說怎麼使用,盡請關注~

  

 

  

  

SpringBoot日記——Redis整合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.