import com.dxy.cache.pojo.Dept;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.net.UnknownHostException;
@Configuration
public class MyRedisConfig {
/**
* 往容器中添加RedisTemplate对象,设置序列化方式
* @param redisConnectionFactory
* @return
* @throws UnknownHostException
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(valueSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(valueSerializer());
template.afterPropertiesSet();
return template;
}
/**
* 往容器中添加RedisCacheManager容器,并设置序列化方式
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
// private final CacheProperties cacheProperties;
//
// MyRedisConfig(CacheProperties cacheProperties) {
// this.cacheProperties = cacheProperties;
// }
/**
* 往容器中添加org.springframework.data.redis.cache.RedisCacheConfiguration 对象
* 目的是为了向默认的RedisCacheManager中设置属性,当然包括序列化
* 如果仅仅是为了设置序列化方式可以和上面的配置二选一
* 在RedisCacheManager内部使用org.springframework.data.redis.cache.RedisCacheConfiguration去保存相关配置信息
*/
// @Bean
// public org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration() {
// CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
// org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
// .defaultCacheConfig();
// config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
// .fromSerializer(valueSerializer()));
// if (redisProperties.getTimeToLive() != null) {
// config = config.entryTtl(redisProperties.getTimeToLive());
// }
// if (redisProperties.getKeyPrefix() != null) {
// config = config.prefixKeysWith(redisProperties.getKeyPrefix());
// }if (!redisProperties.isCacheNullValues()) {
// config = config.disableCachingNullValues();
// }
// if (!redisProperties.isUseKeyPrefix()) {
// config = config.disableKeyPrefix();
// }
// return config;
// }
/**
* 使用Jackson序列化器
* @return
*/
private RedisSerializer<Object> valueSerializer() {
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
/**
* 这一句必须要,作用是序列化时将对象全类名一起保存下来
* 设置之后的序列化结果如下:
* [
* "com.dxy.cache.pojo.Dept",
* {
* "pid": 1,
* "code": "11",
* "name": "财务部1"
* }
* ]
*
* 不设置的话,序列化结果如下,将无法反序列化
*
* {
* "pid": 1,
* "code": "11",
* "name": "财务部1"
* }
*/
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//因为上面那句代码已经被标记成作废,因此用下面这个方法代替,仅仅测试了一下,不知道是否完全正确
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
return serializer;
}
}
import com.dxy.cache.mapper.DeptMapper;
import com.dxy.cache.pojo.Dept;
import com.dxy.cache.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
@Service("deptService")
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
/**
* @Cacheable 包含的属性
* cacheNames/value:缓存的名字
* key:支持SpEL表达式,#id=#a0=#p0=#root.args[0] 都是取出第一个参数的意思
* #result :可以取出返回值
* keyGenerator:key生成器,和key属性二选一
* cacheManager:缓存管理器,获取缓存的
* condition:条件,满足条件时才缓存,如#id>0
* unless:除非,当表达式为true时不缓存 ,如:#result == null
* sync:是否使用异步模式
*
* 缓存原理:
* 1、自动配置 CacheAutoConfiguration
* 2、所有的缓存配置类
* org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
* org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
* org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
* org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
* org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
* org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
* 3、默认情况下,上面的配置类那个生效
* 4、给容器中创建了一个CacheManager:ConcurrentMapCacheManager
* 5、上述CacheManager可以创建和获取ConcurrentMapCache类型的缓存组件,它的作用是将数据存到ConcurrentMap中
*
* 运行流程:
* 1、方法运行之前,去查询Cache(缓存组件),通过配置的cacheNames去查询,第一次会先创建该组件
* 2、去Cache中查询缓存,通过key,默认key是方法参数,使用SimpleKeyGenerator生成key
* SimpleKeyGenerator生成key的策略:
* 如果没有参数:key = new SimpleKey()
* 如果有一个参数:key = 参数的值
* 如果有多个参数:key = new SimpleKey(多个参数)
* 3、如果没有查询到缓存则调用目标方法
* 4、将目标方法的返回值保存到缓存中
*
*
* @param id
* @return
*/
@Cacheable(cacheNames="dept",key="#p0")
@Override
public Dept getDeptById(Long id) {
System.out.println("发起数据库请求");
return deptMapper.getDeptById(id);
}
@Override
public int addDept(Dept dept) {
return deptMapper.addDept(dept);
}
@Override
/**
* 更新缓存,在方法之后执行
*/
@CachePut(cacheNames="dept",key="#p0.pid")
public Dept updateDeptById(Dept dept) {
deptMapper.updateDeptById(dept);
return dept;
}
@Override
/**
* 删除缓存
* 默认在方法执行之后进行缓存删除
* 属性:
* allEntries=true 时表示删除cacheNames标识的缓存下的所有缓存,默认是false
* beforeInvocation=true 时表示在目标方法执行之前删除缓存,默认false
*/
@CacheEvict(cacheNames = "dept",key = "#p0")
public int delDept(Long id) {
return deptMapper.delDept(id);
}
@Override
/**
* 组合@Cacheable、@CachePut、@CacheEvict的一个全面的注解
*/
@Caching(
cacheable = {
@Cacheable(cacheNames = "dept",key="#code")
},
put = {
@CachePut(cacheNames = "dept",key="#result.pid"),
@CachePut(cacheNames = "dept",key="#result.name"),
}
// ,
// evict = {
// @CacheEvict(cacheNames = "dept",key="#code")
// }
)
public Dept getDeptByCode(String code) {
return deptMapper.getDeptByCode(code);
}
}