注解(自定义注解)
* 自定义注解 @Target表示能够放的地方,Type表示可以放在类,接口,注解上
* 还有Method放在方法上,CONSTRUCTOR构造器上
* LOCAL_VARIABLE局部变量上
* 一般自定义的注解Retention(保留策略)选择Runtime,需要用反射添加功能*/
@Target(value={ElementType.FIELD,ElementType.CONSTRUCTOR,ElementType.LOCAL_VARIABLE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnoDemo {
String value();
}
缓存
@Cacheable 将标记的方法结果存入缓存(参数value:指定缓存的名称,参数key:指定存储的key(存储的数据就是value,默认是第一个参数,第一个参数也可以写作#a0),参数condition:满足条件就存入缓存,参数unless:结果为true就不缓存)
@Cacheable(value = "emp",key = "#username",condition = "#a0=='张三'",unless = "#a0=='李四'")
//允许这个方法开启缓存,存入缓存会有个key,key默认为第一个参数
// 其中cacheName跟Value的作用是一样的,指定存的地方叫什么
//condition判断满足条件则缓存,
// 上面a0表示第一个参数,也可以直接写参数username=='张三',可以用and连接多个条件
//unless=""如果为true的话就不缓存
public User querybyname(String username) {
return mapper.querybyname(username);
}
@Cacheput 执行完方法再存入缓存,想要和上面@Cacheable公共缓存就要用一个key,result是方法返回结果。
/**
* Cacheput 执行方法完之后,再将值放入缓存之中.
* 每一个存储的值都有一个key
* key默认存的是第一个参数,这个key需要和查询的key一样
* 下面查询方法的key就是username,result就是返回值*/
@CachePut(value = "emp",key="#result.username")
public User update(User user) {
mapper.update(user);
return user;
}
@CacheEvict 调用标记的方法就会删除缓存,指定key就可以删除对应的缓存
//删除缓存,需要指定删除哪个里面的缓存(用key指定)
@CacheEvict(value = "emp",key="#username")
public String delete(String username){
System.out.println("delete"+username);
return "success";
}
二,用redis作缓存
首先要将redis的配置文件都改好,具体可以看另一个博客。
导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
连接服务器的redis:
配置缓存管理:
存入对象的时候需要改一下序列化规则:
@Bean//改变默认的序列化规则
public RedisTemplate<Object, User> userredisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, User> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<User> ser = new Jackson2JsonRedisSerializer<User>(User.class);
template.setDefaultSerializer(ser);
return template;
}
@Bean//有这个管理的时候可以不需要上面的
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration cacheConfiguration =
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
}
当配置以上东西时,redis就作为了缓存。