Spring Data Redis


關注公眾號:CoderBuff,回復“redis”獲取《Redis5.x入門教程》完整版PDF。

第八章 · Java客戶端(下)

有關本章節源碼:https://github.com/yu-linfeng/redis5.x_tutorial/tree/master/code/spring-data-redis

Java客戶端(上)章節中我們使用了redis的Java客戶端的第三方開源框架——Jedis,但目前Java應用已經被Spring(Spring Boot)統治了大半江山,就連一些數據連接操作的封裝Spring也不放過,這其中也不乏有redis的封裝——Spring Data Redis。關於Spring Data Redis的官方介紹:https://spring.io/projects/spring-data-redis

使用Spring Data Redis后,你會發現一切變得如此簡單,只需要配置文件即可做到開箱即用

我們通過IDEA中的Spring Initializer創建Spring Boot工程,並選擇Spring Data Redis,主要步驟入下圖所示:

第一步,創建工程,選擇Spring Initializr

第二步,選擇SpringBoot的依賴NoSQL -> Spring Data Redis

創建好后,我們通過ymal格式的配置文件application.yml配置相關配置項。

spring:
  redis:
    host: 127.0.0.1
    port: 6379

Spring Data Redis中操作redis的最關鍵的類是RedisTemplate,了解過Spring Data的朋友應該很熟悉~Template后綴,我們在配置好application.yml后直接寫一個測試類體驗一下,什么是開箱即用:

package com.coderbuff.springdataredis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
public class SpringDataRedisApplicationTests {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    void testDefaultRestTemplate() {
        redisTemplate.opsForValue().set("default_redis_template", "1");
    }
}

什么是開箱即用,這就是開箱即用。我們沒有再寫任何的類,只需要兩行配置即可使用。

通常情況下,我們喜歡“封裝”,喜歡把redisTemplate.opsForValue().set這樣的操作封裝成工具類redisUtil.set,所以我們封裝一下RedisTemplate,順帶熟悉它的API。

package com.coderbuff.springdataredis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis操作工具類
 * @author okevin
 * @date 2020/2/18 14:34
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 字符串類型寫入操作
     * @param key key值
     * @param value value值
     */
    public void set(String key, String value) {
        this.redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 可設置過期時間字符串類型寫入操作
     * @param key key值
     * @param value value值
     * @param expire 過期時間
     * @param timeUnit 過期時間單位
     */
    public void set(String key, String value, Long expire, TimeUnit timeUnit) {
        this.redisTemplate.opsForValue().set(key, value, expire, timeUnit);
    }

    /**
     * 字符串類型讀取操作
     * @param key key值
     * @return value值
     */
    public String get(String key) {
        return (String) this.redisTemplate.opsForValue().get(key);
    }
}

編寫測試類:

package com.coderbuff.springdataredis.util;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author okevin
 * @date 2020/2/18 23:14
 */
@SpringBootTest
public class RedisUtilTests {

    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void testSet() {
        redisUtil.set("redis_util", "1");
        Assertions.assertEquals("1", redisUtil.get("redis_util"));
    }
}

實際上,真正要把Spring Data Redis用好,還可以做以下工作:

  • 把redis作為Spring的緩存管理

注意本文使用的是SpringBoot2.x與SpringBoot1.x有一定的區別。

package com.coderbuff.springdataredis.config;

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.RedisConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * redis配置
 * @author okevin
 * @date 2020/2/18 14:20
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 使用redis作為spring的緩存管理工具
     * 注意:springboot2.x與springboot1.x此處的區別較大
     * 在springboot1.x中,要使用redis的緩存管理工具為以下代碼:
     *
     * public CacheManager cacheManager(RedisTemplate redisTemplate) {
     *     RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
     *     return redisCacheManager;
     * }
     *
     * @param redisConnectionFactory redis連接工廠
     * @return redis緩存管理
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheManager redisCacheManager = RedisCacheManager.create(redisConnectionFactory);
        return redisCacheManager;
    }
}
  • 盡管SpringBoot已經為我們構造好了RedisTemplate,但我們可能還是需要定制化注入RedisTemplate

我們可以定制RedisTemplate,例如序列化的方式等,當然這些都不是必須的:

package com.coderbuff.springdataredis.config;

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.RedisTemplate;

/**
 * redis配置
 * @author okevin
 * @date 2020/2/18 14:20
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    //省略上面的cacheManager注入

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);     //配置連接工廠

        /*使用Jackson序列化和反序列化key、value值,默認使用JDK的序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  //指定要序列化的域,ALL表示所有字段、以及set/get方法,ANY是都有包括修飾符private和public
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);   //指定序列化輸入的類型,NON_FINAL表示必須是非final修飾的類型
        jacksonSeial.setObjectMapper(om);

        //以下數據類型通過jackson序列化
        redisTemplate.setValueSerializer(jacksonSeial);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jacksonSeial);
        */
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

想要學習更多Spring Data Redis,就請打開官網(https://spring.io/projects/spring-data-redis)盡情探索吧。

關注公眾號:CoderBuff,回復“redis”獲取《Redis5.x入門教程》完整版PDF。

這是一個能給程序員加buff的公眾號 (CoderBuff)


免責聲明!

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



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