1. 程式人生 > 實用技巧 >SpringBoot+MyBatis+Redis(二級快取)

SpringBoot+MyBatis+Redis(二級快取)

應用場景:
儲存大資料量,避免重複請求。

一、新增Maven依賴

<!-- SpringBoot Boot Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、編寫Redis相關類

RedisService.java

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@SuppressWarnings(value 
= { "unchecked", "rawtypes" }) @Component public class RedisService { @Autowired public RedisTemplate redisTemplate; /** * 快取基本的物件,Integer、String、實體類等 * * @param key 快取的鍵值 * @param value 快取的值 */ public <T> void setCacheObject(final String key, final T value) { redisTemplate.opsForValue().
set(key, value); } /** * 快取基本的物件,Integer、String、實體類等 * * @param key 快取的鍵值 * @param value 快取的值 * @param timeout 時間 * @param timeUnit 時間顆粒度 */ public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) { redisTemplate.opsForValue().
set(key, value, timeout, timeUnit); } /** * 設定有效時間 * * @param key Redis鍵 * @param timeout 超時時間 * @return true=設定成功;false=設定失敗 */ public boolean expire(final String key, final long timeout) { return expire(key, timeout, TimeUnit.SECONDS); } /** * 設定有效時間 * * @param key Redis鍵 * @param timeout 超時時間 * @param unit 時間單位 * @return true=設定成功;false=設定失敗 */ public boolean expire(final String key, final long timeout, final TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); } /** * 獲得快取的基本物件。 * * @param key 快取鍵值 * @return 快取鍵值對應的資料 */ public <T> T getCacheObject(final String key) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); return operation.get(key); } /** * 刪除單個物件 * * @param key */ public boolean deleteObject(final String key) { return redisTemplate.delete(key); } /** * 刪除集合物件 * * @param collection 多個物件 * @return */ public long deleteObject(final Collection collection) { return redisTemplate.delete(collection); } /** * 快取List資料 * * @param key 快取的鍵值 * @param dataList 待快取的List資料 * @return 快取的物件 */ public <T> long setCacheList(final String key, final List<T> dataList) { Long count = redisTemplate.opsForList().rightPushAll(key, dataList); return count == null ? 0 : count; } /** * 獲得快取的list物件 * * @param key 快取的鍵值 * @return 快取鍵值對應的資料 */ public <T> List<T> getCacheList(final String key) { return redisTemplate.opsForList().range(key, 0, -1); } /** * 快取Set * * @param key 快取鍵值 * @param dataSet 快取的資料 * @return 快取資料的物件 */ public <T> long setCacheSet(final String key, final Set<T> dataSet) { Long count = redisTemplate.opsForSet().add(key, dataSet); return count == null ? 0 : count; } /** * 獲得快取的set * * @param key * @return */ public <T> Set<T> getCacheSet(final String key) { return redisTemplate.opsForSet().members(key); } /** * 快取Map * * @param key * @param dataMap */ public <T> void setCacheMap(final String key, final Map<String, T> dataMap) { if (dataMap != null) { redisTemplate.opsForHash().putAll(key, dataMap); } } /** * 獲得快取的Map * * @param key * @return */ public <T> Map<String, T> getCacheMap(final String key) { return redisTemplate.opsForHash().entries(key); } /** * 往Hash中存入資料 * * @param key Redis鍵 * @param hKey Hash鍵 * @param value 值 */ public <T> void setCacheMapValue(final String key, final String hKey, final T value) { redisTemplate.opsForHash().put(key, hKey, value); } /** * 獲取Hash中的資料 * * @param key Redis鍵 * @param hKey Hash鍵 * @return Hash中的物件 */ public <T> T getCacheMapValue(final String key, final String hKey) { HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash(); return opsForHash.get(key, hKey); } /** * 獲取多個Hash中的資料 * * @param key Redis鍵 * @param hKeys Hash鍵集合 * @return Hash物件集合 */ public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) { return redisTemplate.opsForHash().multiGet(key, hKeys); } /** * 獲得快取的基本物件列表 * * @param pattern 字串字首 * @return 物件列表 */ public Collection<String> keys(final String pattern) { return redisTemplate.keys(pattern); } }

RedisConfig.java

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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes", "deprecation" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(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;
    }
}

RedisCache.java

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final String id;
    private RedisTemplate redisTemplate;
    //redis過期時間
    private static final long EXPIRE_TIME_IN_MINUTES = 30;

    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instance required an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    /**
     * Put query result to redis
     *
     * @Param key
     * @Param value
     */
    @Override
    public void putObject(Object key, Object value) {
        RedisTemplate redisTemplate = getRedisTemplate();
        ValueOperations opsForValue = redisTemplate.opsForValue();
        System.out.println(key + ": key");
        System.out.println(key.toString() + ": key.toString()");
        System.out.println(value + ": value");
        System.out.println(value.toString() + ": value.toString()");
        opsForValue.set(key.toString(), value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
        System.out.println("結果成功放入快取 and " + "key = " + "\n" + key + "value = " + value);
        System.out.println(opsForValue.get(key.toString()));
    }

    /**
     * Get cached query result to redis
     *
     * @Param key
     * @Return
     */
    @Override
    public Object getObject(Object key) {
        RedisTemplate redisTemplate = getRedisTemplate();
//        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        ValueOperations opsForValue = redisTemplate.opsForValue();
        System.out.println("結果從快取中獲取");
        return opsForValue.get(key.toString());
    }

    /**
     * Remove cached query result to redis
     *
     * @Param key
     * @Return
     */
    @Override
    public Object removeObject(Object key) {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.delete(key);
        System.out.println("從快取中刪除");
        return null;
    }

    /**
     * Clear this cache instance
     */
    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        System.out.println("清空快取");
    }

    @Override
    public int getSize() {
        Long size = (Long) redisTemplate.execute((RedisCallback) connection -> connection.dbSize());
        return size.intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }
}

三、yml配置redis

spring:
  redis:
    host: localhost
    port: 6379
    password:

四、在DAO類新增該註解

@CacheNamespace(implementation = RedisCache.class)

五、實現類或者在Controller加如下程式碼,鍵值對儲存對應的資料

@Autowired
private RedisService redisService;

六、如何確保Redis資料實時更新

我研究了下,通常如下:
1.先刪快取,再更新資料庫
2.先寫資料庫,再刪快取
參考:
Redis快取如何保證一致性

補充:
Redis 和 Mysql 資料庫資料如何保持一致性