springboot整合redis——redisTemplate的使用


一、概述

  相關redis的概述,參見Nosql章節

  redisTemplate的介紹,參考http://blog.csdn.net/ruby_one/article/details/79141940

  StringRedisTemplate作為RedisTemplate的子類,只支持KV為String的操作

StringRedisTemplate與RedisTemplate
兩者的關系是StringRedisTemplate繼承RedisTemplate。

兩者的數據是不共通的;也就是說StringRedisTemplate只能管理StringRedisTemplate里面的數據,
RedisTemplate只能管理RedisTemplate中的數據。 SDR默認采用的序列化策略有兩種,一種是String的序列化策略,一種是JDK的序列化策略。 StringRedisTemplate默認采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。 RedisTemplate默認采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。

  更多文檔,參考javadoc:點擊查看

  其他實戰:參考碼雲springboot全家桶等!

二、入門

  1.安裝windows版redis

    由於windows的redis僅僅用於個人測試玩耍,這里就簡單下載zip解壓版本,相關配置項也不在這里贅述,參考linux下redis的介紹

    點擊下載:https://github.com/MicrosoftArchive/redis/releases

      下載后解壓;

     在解壓所在目錄使用如下命令啟動服務端:(由於這里使用的win10的powershell,所以需要添加./,或者配置環境變量也可以避免使用./)

./redis-server.exe redis.windows.conf

    // 這里就不將其注冊為windows服務了,關閉窗口,也就關閉了redis

    啟動命令端:

./redis-cli.exe -h 127.0.0.1 -p 6379

  2.引入依賴

 <!-- springboot整合redis -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-data-redis</artifactId>  
        </dependency> 

  這里只需引入這一個redis的依賴即可,其他3個自動進行了依賴:

  

  3.在application.yml中配置redis

#redis 
spring.redis.hostName=127.0.0.1 spring.redis.port=6379 spring.redis.pool.maxActive=8 spring.redis.pool.maxWait=-1 spring.redis.pool.maxIdle=8 spring.redis.pool.minIdle=0 spring.redis.timeout=0 

  // yml中改為yml的寫法:

# redis配置,以下有默認配置的也可以使用默認配置
  redis:
    host: 127.0.0.1
    port: 6379
    pool:
      max-active: 8
      max-wait: 1
      max-idle: 8
      min-idle: 0
    timeout: 0

  // 有許多的默認配置,可以直接使用默認

  如果換成了集群方式,配置修改入如下所示:

spring:
    application:
        name: spring-boot-redis
    redis:
        host: 192.168.145.132
        port: 6379
        timeout: 20000
        cluster:
            nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002
            maxRedirects: 6
        pool:
            max-active: 8
            min-idle: 0
            max-idle: 8
            max-wait: -1

  // 對應的配置類:org.springframework.boot.autoconfigure.data.redis.RedisProperties

  4.建立redis配置類

package com.example.demo.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * redis配置類 * * @author zcc ON 2018/3/19 **/ @Configuration @EnableCaching//開啟注解
public class RedisConfig { @Bean public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) { CacheManager cacheManager = new RedisCacheManager(redisTemplate); return cacheManager; /*RedisCacheManager rcm = new RedisCacheManager(redisTemplate); // 多個緩存的名稱,目前只定義了一個 rcm.setCacheNames(Arrays.asList("thisredis")); //設置緩存默認過期時間(秒) rcm.setDefaultExpiration(600); return rcm;*/ } // 以下兩種redisTemplate自由根據場景選擇
 @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(factory); return stringRedisTemplate; } }

  5.編寫相關的實體類

    這里注意一定要實現序列化接口用於序列化!

public class Girl implements Serializable{ private static final long serialVersionUID = -3946734305303957850L;

  // IDEA開啟Java的檢查即可自動生成!

  6.相關的service

    處理緩存相關的前綴的常量類:

 

public class RedisKeyPrefix { private RedisKeyPrefix() { } public static final String GIRL = "girl:"; }

 

 

 

  /** * 通過id查詢,如果查詢到則進行緩存 * @param id 實體類id * @return 查詢到的實現類 */
    public Girl findOne(Integer id) { String key = RedisKeyPrefix.GIRL + id; // 緩存存在
        boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { // 從緩存中取
            Girl girl = redisTemplate.opsForValue().get(key); log.info("從緩存中獲取了用戶!"); return girl; } // 從數據庫取,並存回緩存
        Girl girl = girlRepository.findOne(id); // 放入緩存,並設置緩存時間
        redisTemplate.opsForValue().set(key, girl, 600, TimeUnit.SECONDS); return girl; }

  特別注意的是這里的注入,由於之前配置了redisTemplate及其子類,故需要使用@Resource注解進行!

@Resource private RedisTemplate<String, Girl> redisTemplate; // private RedisTemplate<String, Object> redisTemplate;根據實際情況取泛型

  剩下的刪除和更新也是對應的操作緩存,參考網友的寫法:

/** * 更新用戶 * 如果緩存存在,刪除 * 如果緩存不存在,不操作 * * @param user 用戶 */
    public void updateUser(User user) { logger.info("更新用戶start..."); userMapper.updateById(user); int userId = user.getId(); // 緩存存在,刪除緩存
        String key = "user_" + userId; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); logger.info("更新用戶時候,從緩存中刪除用戶 >> " + userId); } } /** * 刪除用戶 * 如果緩存中存在,刪除 */
    public void deleteById(int id) { logger.info("刪除用戶start..."); userMapper.deleteById(id); // 緩存存在,刪除緩存
        String key = "user_" + id; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); logger.info("刪除用戶時候,從緩存中刪除用戶 >> " + id); } }

  更多基本用法,參考http://blog.csdn.net/ruby_one/article/details/79141940

三、注意事項與相關問題

  1.數據同步問題

redis和mysql數據的同步,代碼級別大致可以這樣做: 讀: 讀redis->沒有,讀mysql->把mysql數據寫回redis 寫: 寫mysql->成功,寫redis

  2.統一管理key 前綴

    通過常量類的形式(阿里的解決方案),當然,通過配置properties 等也是闊以的

  3.開發規范

    參考nosql 入門章節介紹


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM