SpringBoot Redis快取配置
阿新 • • 發佈:2022-11-30
config
/** * create by fzg * 2022/7/27 11:18 */ 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.RedisCacheConfiguration; 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.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; @EnableCaching @Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解決查詢快取轉換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解決亂碼的問題),過期時間600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
工具類
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; @Slf4j @Component public class CacheService { @Autowired private StringRedisTemplate redisTemplate; private final String DEFAULT_KEY_PREFIX = ""; private final int EXPIRE_TIME = 1; private final TimeUnit EXPIRE_TIME_TYPE = TimeUnit.DAYS; /** * 資料快取至redis * * @param key * @param value * @return */ public <K, V> void add(K key, V value) { try { if (value != null) { redisTemplate .opsForValue() .set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value)); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("資料快取至redis失敗"); } } /** * 資料快取至redis並設定過期時間 * * @param key * @param value * @return */ public <K, V> void add(K key, V value, long timeout, TimeUnit unit) { try { if (value != null) { redisTemplate .opsForValue() .set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value), timeout, unit); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("資料快取至redis失敗"); } } /** * 寫入 hash-set,已經是key-value的鍵值,不能再寫入為hash-set * * @param key must not be {@literal null}. * @param subKey must not be {@literal null}. * @param value 寫入的值 */ public <K, SK, V> void addHashCache(K key, SK subKey, V value) { redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value); } /** * 寫入 hash-set,並設定過期時間 * * @param key must not be {@literal null}. * @param subKey must not be {@literal null}. * @param value 寫入的值 */ public <K, SK, V> void addHashCache(K key, SK subKey, V value, long timeout, TimeUnit unit) { redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value); redisTemplate.expire(DEFAULT_KEY_PREFIX + key, timeout, unit); } /** * 獲取 hash-setvalue * * @param key must not be {@literal null}. * @param subKey must not be {@literal null}. */ public <K, SK> Object getHashCache(K key, SK subKey) { return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX + key, subKey); } /** * 從redis中獲取快取資料,轉成物件 * * @param key must not be {@literal null}. * @param clazz 物件型別 * @return */ public <K, V> V getObject(K key, Class<V> clazz) { String value = this.get(key); V result = null; if (!StringUtils.isEmpty(value)) { result = JSONObject.parseObject(value, clazz); } return result; } /** * 從redis中獲取快取資料,轉成list * * @param key must not be {@literal null}. * @param clazz 物件型別 * @return */ public <K, V> List<V> getList(K key, Class<V> clazz) { String value = this.get(key); List<V> result = Collections.emptyList(); if (!StringUtils.isEmpty(value)) { result = JSONArray.parseArray(value, clazz); } return result; } /** * 功能描述:Get the value of {@code key}. * * @param key must not be {@literal null}. * @return java.lang.String * @date 2021/9/19 **/ public <K> String get(K key) { String value; try { value = redisTemplate.opsForValue().get(DEFAULT_KEY_PREFIX + key); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("從redis快取中獲取快取資料失敗"); } return value; } /** * 刪除key */ public void delete(String key) { redisTemplate.delete(key); } /** * 批量刪除key */ public void delete(Collection<String> keys) { redisTemplate.delete(keys); } /** * 序列化key */ public byte[] dump(String key) { return redisTemplate.dump(key); } /** * 是否存在key */ public Boolean hasKey(String key) { return redisTemplate.hasKey(key); } /** * 設定過期時間 */ public Boolean expire(String key, long timeout, TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); } /** * 設定過期時間 */ public Boolean expireAt(String key, Date date) { return redisTemplate.expireAt(key, date); } /** * 移除 key 的過期時間,key 將持久保持 */ public Boolean persist(String key) { return redisTemplate.persist(key); } /** * 返回 key 的剩餘的過期時間 */ public Long getExpire(String key, TimeUnit unit) { return redisTemplate.getExpire(key, unit); } /** * 返回 key 的剩餘的過期時間 */ public Long getExpire(String key) { return redisTemplate.getExpire(key); } }