1、使用情况
缓存的适用情况:查询内容长久不变的、读写比很大的(读写1:10)前后端一致性需求不高的 可以使用缓存
方法一 Springboot基于注解的缓存 @EnableCaching(proxyTargetClass=true) //开启支持缓存的注解 并基于类进行代理
常用注解:
@Cacheable //添加缓存 public List<User> findAllUser(){return list}
@CacheEvict //清理缓存 public void reloadUser(){}
@CachePut
@Caching
@CacheConfig
缺点:不能配置超时时间
方法二 Springboot基于Redis进行缓存 (可以设置过期时间)
application.properties 一定要设置过期时间
spring.cache.type=redis
spring.cache.cache-names=user
spring.cache.redis.time-to-live=5000
spring.cache.redis.cache-null-values=false
spring.redis.host=192.168.114.131
pom依赖
<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>
@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl {
@Autowired
UserRepository userRepository;
@Cacheable
public List<User> findAll(){
return userRepository.findAll();
}
@CacheEvict
public void reloadUser(){}
}
@SpringBootApplication
@EnableCaching(proxyTargetClass = true)
public class RibiApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(RibiApplication.class, args);
}
@Autowired
private UserServiceImpl service;
@Override
public void run(ApplicationArguments args) throws Exception{
service.findAll().stream().forEach(x->{System.out.print(x);});
for (int i=0;i<10;i++){
service.findAll().stream().forEach(x->{System.out.print(x);});
}
service.reloadUser();
service.findAll().stream().forEach(x->{System.out.print(x);});
}
}
运行期间查看redis
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> keys *
1) "user::SimpleKey []"
已存在于redis
-- 部分摘自 极客时间 玩转Spring全家桶