一、使用cache
1. 激活缓存
@EnableCaching(proxyTargetClass = true)
2. 配置
使用redis做缓存,注意一定要设置超时时间,主要是为了放置缓存只增不减占用内存(导致redis服务崩溃),如果需要长期保留缓存,只要在超时到期前作延期就行了。
spring.cache.type=redis
spring.cache.cache-names=ssssstudent
spring.cache.redis.time-to-live=15000
spring.cache.redis.cache-null-values=false
spring.redis.host=localhost
spring.redis.database=0
3. service中使用cache
主要使用
- @Cacheable
- @CachePut
- @CacheEvict
package com.example.cache.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.example.cache.mapper.StudentMapper;
import com.example.cache.model.Student;
import lombok.extern.slf4j.Slf4j;
@Service
@CacheConfig(cacheNames = "student")
@Slf4j
public class StudentService {
@Autowired
private StudentMapper studentMapper;
@Cacheable
public Student findStudentById(Integer id) {
log.info("findStudentById id=[" + id + "] from h2");
return studentMapper.findById(id);
}
@CacheEvict(key = "1")
public void evitStudent() {
}
}