1、修改application.properties中redis主机+端口号
spring.redis.host=192.168.91.100
spring.redis.port=6379
2、在springboob启动类上面加上注解,开启缓存注解
@EnableCaching
3、springboot默认的序列化方式是jdk,添加配置使用jackson方式序列化
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
@Configuration
public class RedisConfig {
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
RedisCacheConfiguration config = RedisCacheConfiguration
.defaultCacheConfig();
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
//把默认的jdk的序列化方式变成jackson
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
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;
}
}
4、在方法上加入注解
cacheNames: 缓存的前缀名称 key:缓存的后缀名称。
@CachePut: 先修改数据库,再修改缓存,如果缓存中没有则放入到缓存中该对象。
@CacheEvict: 删除数据库并删除缓存。
@Cacheable: 先查询缓存,缓存中如果存在,则直接返回,如果不存在则执行方法体。并把方法体中执行的结果放入到缓存中。
@Override
@CacheEvict(cacheNames = "user",key = "#id")
public int deleteByPrimaryKey(Integer id) {
return userMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
@Cacheable(cacheNames = "user",key = "#id")
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
@Override
@CachePut(cacheNames = "user",key = "#record.id")
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}
@Override
public List<UserWithDepartment> selectUserWithDepart() {
return userMapper.selectUserWithDepart();
}