参考文章
springboot缓存
1、引用jia包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、Spring Boot入口类中加入@EnableCaching注解开启缓存功能
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3、方法上加入缓存
@CacheConfig(cacheNames = "student")
public interface StudentService {
@CachePut(key = "#p0.sno")
Student update(Student student);
@CacheEvict(key = "#p0")
void deleteStudentBySno(String sno);
@Cacheable(key = "#p0")
Student queryStudentBySno(String sno);
}
缓存注解说明:
@CacheConfig:主要用于配置该类中会用到的一些共用的缓存配置。在这里@CacheConfig(cacheNames = “student”):配置了该数据访问对象中返回的内容将存储于名为student的缓存对象中,我们也可以不使用该注解,直接通过@Cacheable自己配置缓存集的名字来定义;
@Cacheable:配置了queryStudentBySno函数的返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问。该注解主要有下面几个参数:
- value、cacheNames:两个等同的参数(cacheNames为Spring
4新增,作为value的别名),用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig,因此在Spring
3中原本必须有的value属性,也成为非必需项了; - key:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如:@Cacheable(key
= “#p0”):使用函数第一个参数作为缓存的key值,更多关于SpEL表达式的详细内容可参考https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache; - condition:缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存,比如:@Cacheable(key
= “#p0”, condition = “#p0.length() < 3”),表示只有当第一个参数的长度小于3的时候才会被缓存; - unless:另外一个缓存条件参数,非必需,需使用SpEL表达式。它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以通过对result进行判断;
- keyGenerator:用于指定key生成器,非必需。若需要指定一个自定义的key生成器,我们需要去实现org.springframework.cache.interceptor.KeyGenerator接口,并使用该参数来指定;
- cacheManager:用于指定使用哪个缓存管理器,非必需。只有当有多个时才需要使用;
- cacheResolver:用于指定使用那个缓存解析器,非必需。需通过org.springframework.cache.interceptor.CacheResolver接口来实现自己的缓存解析器,并用该参数指定;
@CachePut:清除之前的缓存,调用方法,把结果重新放入缓存。它的参数与@Cacheable类似,具体功能可参考上面对@Cacheable参数的解析;
@CacheEvict:配置于函数上,通常用在删除方法上,用来从缓存中移除相应数据。除了同@Cacheable一样的参数之外,它还有下面两个参数:
- allEntries:非必需,默认为false。当为true时,会移除所有数据;
- beforeInvocation:非必需,默认为false,会在调用方法之后移除数据。当为true时,会在调用方法之前移除数据。
redis
1、在application.yml中配置Redis:
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: localhost
# Redis服务器连接端口
port: 6379
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 0
2、创建一个Redis配置类
package com.springboot.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
// 自定义缓存key生成策略
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName()).append(":").append(method.getName());
for (Object obj : params) {
sb.append(":").append(obj.toString());
}
return sb.toString();
}
};
}
// 缓存管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间
cacheManager.setDefaultExpiration(10000);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);// 设置序列化工具
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template) {
@SuppressWarnings({"rawtypes", "unchecked"})
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
3、如果要使用自定义的KeyGenerator,@Cacheable 不能使用key
@CacheConfig(cacheNames = "user")
public interface UserService {
@CacheEvict(allEntries = true)
User update(User student);
@CacheEvict(allEntries = true)
void deleteUserBySno(String sno);
@Cacheable
User queryUserBySno(String sno);
}
1、测试
@Test
public void test1() throws Exception {
Student student1 = this.studentService.queryStudentBySno("001");
System.out.println("学号" + student1.getSno() + "的学生姓名为:" + student1.getName());
Student student2 = this.studentService.queryStudentBySno("001");
System.out.println("学号" + student2.getSno() + "的学生姓名为:" + student2.getName());
User user1 = this.userService.queryUserBySno("001");
System.out.println("ID " + user1.getSno() + "的用户姓名为:" + user1.getName());
User user2 = this.userService.queryUserBySno("001");
System.out.println("ID " + user2.getSno() + "的用户姓名为:" + user2.getName());
}
运行结果
从数据库查询数据 sno :001
学号001的学生姓名为:小红
学号001的学生姓名为:小红
从数据库查询数据 sno :001
ID 001的用户姓名为:小明
ID 001的用户姓名为:小明
第一次查询走数据库,第二次查询走缓存,如下图。红色的是student,绿色的是user
2、测试
@Test
public void test3() {
User user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的用户姓名为:" + user1.getName());
user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的用户姓名为:" + user1.getName());
user1.setName("康康");
this.userService.update(user1);
user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的用户姓名为:" + user1.getName());
user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的用户姓名为:" + user1.getName());
}
运行结果:
从数据库查询数据 sno :001
Id001的用户姓名为:小明
Id001的用户姓名为:小明
修改数据 :{"name":"康康","sex":"man","sno":"001"}
从数据库查询数据 sno :001
Id001的用户姓名为:小明
Id001的用户姓名为:小明
第一次查询走数据库,第二次走缓存,修改后清空缓存,第三次走数据库,第四次走缓存