@Cacheable使用

一、常见使用@Cacheable

自定义生成key

/**
 * 根据方法的参数 生成唯一的缓存Key
 */
@Component
public class SelfKeyGenerate implements KeyGenerator {
	@Override
	public Object generate(Object target, Method method, Object... params) {
		return target.getClass().getSimpleName() + "_"
				+ method.getName() + "_"
				+ StringUtils.arrayToDelimitedString(params, "_");

	}
}

常见使用
结果为空,不加入缓存

@Cacheable(value = "product:list",keyGenerator = "selfKeyGenerate", unless = "#result == null")

二、@Cacheable设置失效时间

package com.framework.cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * RedisConfigCacheManager
 */
@Slf4j
public class RedisConfigCacheManager extends RedisCacheManager {


	public RedisConfigCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
		super(cacheWriter, defaultCacheConfiguration);
	}

	private static final RedisSerializationContext.SerializationPair<Object> DEFAULT_PAIR = RedisSerializationContext.SerializationPair
			.fromSerializer(new GenericJackson2JsonRedisSerializer());

	private static final CacheKeyPrefix DEFAULT_CACHE_KEY_PREFIX = cacheName -> cacheName+":";

	@Override
	protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
		final int lastIndexOf = StringUtils.lastIndexOf(name, '#');
		if (lastIndexOf > -1) {
			final String ttl = StringUtils.substring(name, lastIndexOf + 1);
			final Duration duration = Duration.ofSeconds(Long.parseLong(ttl));
			cacheConfig = cacheConfig.entryTtl(duration);
			//修改缓存key和value值的序列化方式
			cacheConfig = cacheConfig.computePrefixWith(DEFAULT_CACHE_KEY_PREFIX)
					.serializeValuesWith(DEFAULT_PAIR);
			final String cacheName = StringUtils.substring(name, 0, lastIndexOf);
			return super.createRedisCache(cacheName, cacheConfig);
		}else{
			//修改缓存key和value值的序列化方式
			cacheConfig = cacheConfig.computePrefixWith(DEFAULT_CACHE_KEY_PREFIX)
					.serializeValuesWith(DEFAULT_PAIR);
			return super.createRedisCache(name, cacheConfig);
		}
	}


}

RedisConfig配置

package com.framework.config;

import com.framework.cache.RedisConfigCacheManager;
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.RedisCacheWriter;
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 com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.Duration;

/**
 * redis配置
 *
 * @author 
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
	@Bean
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	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;
	}

	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

		ObjectMapper om = new ObjectMapper();
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
				Object.class);
		// 解决查询缓存转换异常的问题
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		// 配置序列化(解决乱码的问题)
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
				.entryTtl(Duration.ofMillis(-1))
				.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
				.disableCachingNullValues();
		RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

		return new RedisConfigCacheManager(cacheWriter, config);


	}
}

使用

@Cacheable(value = "category:list#3600", keyGenerator = "selfKeyGenerate",unless = "#result == null")

你可能感兴趣的:(springboot,java)