SpringBoot使用RedisTemplate整合Redis


  這兩天寫了寫登錄的邏輯, 從剛開始用cookie, 到用jwt token, 到單點登錄, 隨着系統的不斷升級, 所用技術也在隨之改變升級.  其中也遇到了一些坑, 尤其今天是redis 作為存儲token的內存數據庫.  之前用過

SpringBoot使用RedisTemplate整合Redis, 然后沒寫博客記錄下, 結果今天再重新用的話, 還是要去看看資料什么的. 我想想還是記錄一下比較好.  整理博客,寫博客的事也要按計划進行

  Springboot整合Redis有兩種方式,分別是Jedis和RedisTemplate,這兩者有何區別?Jedis是Redis官方推薦的面向Java的操作Redis的客戶端,而RedisTemplate是SpringDataRedis中對JedisApi的高度封裝。其實在Springboot的官網上我們也能看到,官方現在推薦的是SpringDataRedis形式,相對於Jedis來說可以方便地更換Redis的Java客戶端,其比Jedis多了自動管理連接池的特性,方便與其他Spring框架進行搭配使用如:SpringCache。不過jedis 方式能很清楚的看到其基本的工作方式,對Redis連接池的手動管理都能更清晰地體現出來。

  RedisTemplate官網文檔地址:
  https://docs.spring.io/spring-data/redis/docs/2.0.3.RELEASE/reference/html/#redis:template

  對於redis 底層原理, 一些數據結構, 安裝設計什么的, 我建議可以閱讀平凡希大佬的博客, 他寫的博客還是很牛逼的. https://www.cnblogs.com/xiaoxi/

springboot 與redis的整合

pom文件

  依賴如下:

    <dependencies>
<!-- redis -->
      <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-redis</artifactId>
<!--         <version>2.0.9.RELEASE</version>-->
      </dependency>
      <dependency>
         <groupId>redis.clients</groupId>
         <artifactId>jedis</artifactId>
<!--         <version>2.9.0</version>-->
      </dependency>
 </dependencies>

application.properties

  # Redis數據庫索引(默認為0)
  spring.redis.database=0  
  # Redis服務器地址
  spring.redis.host=127.0.0.1
  # Redis服務器連接端口
  spring.redis.port=6379  
  # Redis服務器連接密碼(默認為空)
  spring.redis.password=
  # 連接池最大連接數(使用負值表示沒有限制)
  spring.redis.pool.max-active=200
  # 連接池最大阻塞等待時間(使用負值表示沒有限制)
  spring.redis.pool.max-wait=3000
  # 連接池中的最大空閑連接
  spring.redis.pool.max-idle=20
  # 連接池中的最小空閑連接
  spring.redis.pool.min-idle=10
  # 連接超時時間(毫秒)
  spring.redis.timeout=2000

redisTemplate的配置

  新建一個redisConfig類,進行相關bean的配置:

package com.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.CachingConfigurerSupport;
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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author janti
 * reids 相關bean的配置
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 選擇redis作為默認緩存工具
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }

    /**
     * retemplate相關配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置連接工廠
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用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等會跑出異常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 設置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 對hash類型的數據操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 對redis字符串類型數據操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 對鏈表類型的數據操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 對無序集合類型的數據操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 對有序集合類型的數據操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}
  • spring-redis中使用了RedisTemplate來進行redis的操作,通過泛型的K和V設置鍵值對的對象類型。這里使用了string作為key的對象類型,值為Object。

  • 對於Object,spring-redis默認使用了jdk自帶的序列化,不推薦使用默認了。所以使用了json的序列化方式

  • 對spring-redis對redis的五種數據類型也有支持

  • HashOperations:對hash類型的數據操作

  • ValueOperations:對redis字符串類型數據操作

  • ListOperations:對鏈表類型的數據操作

  • SetOperations:對無序集合類型的數據操作

  • ZSetOperations:對有序集合類型的數據操作

測試類

@RunWith(SpringRunner.class)

@SpringBootTest

public class RedisConfigTest {

    @Autowired private RedisTemplate redisTemplate;

    @Test public void test() throws Exception{

        ValueOperations<String,Object>  valueOperations = redisTemplate.opsForValue();

        valueOperations.set("shanghai","shanghai",20, TimeUnit.SECONDS); // 新增, 設置失效時間

        valueOperations.set("hebei","shijiazhuang2"); // 存在的話就是修改

        Object hebei = valueOperations.get("hebei");
 

    }

}

  像刪除值, 刪除主鍵這些操作可以查看官方文檔或者百度搜索.  創建工具類什么的可以結合自己實際業務來寫

注解緩存的使用

  • @Cacheable:在方法執行前Spring先查看緩存中是否有數據,如果有數據,則直接返回緩存數據;沒有則調用方法並將方法返回值放進緩存。

  • @CachePut:將方法的返回值放到緩存中。

  • @CacheEvict:刪除緩存中的數據。

TimeUnit

TimeUnit.DAYS          //天
TimeUnit.HOURS         //小時
TimeUnit.MINUTES       //分鍾
TimeUnit.SECONDS       //秒
TimeUnit.MILLISECONDS  //毫秒 

 


免責聲明!

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



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