- 一、spring 缓存 @CachePut 和 @Cacheable 区别
- 二、缓存注解@CachePut属性key拼接
- 三、Spring Cacheable注解不缓存null值
- 四、@CacheConfig
- 五、Springboot配置RedisConfig
- 六、使用
首先这两个的区别是:
@CachePut:新增、编辑缓存 这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中。
@Cacheable:查询缓存当重复使用相同参数调用方法的时候,方法本身不会被调用执行,即方法本身被略过了,取而代之的是方法的结果直接从缓存中找到并返回了。
总结:@CachePut和@Cacheable这两个标签可以结合使用,当需要根据请求改变值的时候,利用@CachePut将值改变并写入到缓存中,而@Cacheable标签除了第一次之外,一直是取的缓存的值。
二、缓存注解@CachePut属性key拼接//@CachePut(key="#user.name")//正常情况#user.name就可以了
@CachePut(key="'huawei_' + #user.name")//#user.name获取的是参数user中的name属性值
@Override
public User updateUser(User user) {
//新增、编辑
return user;
}
key拼接: 单引号内是自定义的
三、Spring Cacheable注解不缓存null值用Cacheable注解时,发现空值,也会被缓存下来,正常情况缓存null了,缓存才能发挥作用,不然很多空值重复查询数据库,但是需求有直接改数据库的操作,需要把空值过滤掉,不然会一直返回null
@Cacheable(unless="#result == null")
@Override
public User getByName(String name) {
return userMapper.getByName(name);
}
这样,当方法返回空值时,就不会被缓存起来。
四、@CacheConfig@CacheConfig用于类上, cacheNames = "person"相当于key的前缀,最后结果是person::huawei_zhangsan
@CacheConfig(cacheNames = "person")
public class UserServiceImpl implements UserService {
}
五、Springboot配置RedisConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import lombok.extern.slf4j.Slf4j;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
@Slf4j
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
log.info(" --- redis config init --- ");
// 设置序列化
Jackson2JsonRedisSerializer
六、使用
- 配置RedisConfig
- 在类上加@CacheConfig(cacheNames = “person”)
@CacheConfig(cacheNames = "person")
public class UserServiceImpl implements UserService {
}
- 新增编辑方法上加@CachePut
@CachePut(key="#user.name")//#user.name获取的是参数user中的name属性值
@Override
public User updateUser(User user) {
//新增、编辑
return user;
}
- 查询方法上加@Cacheable, key就是name属性值
@Cacheable
@Override
public User getByName(String name) {
return userMapper.getByName(name);
}



