1、main启动类加入@EnableCaching
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
2、自定义缓存key的命名规则
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
// 自定义缓存的 key生成
@Component
public class MyKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(o.getClass().getSimpleName())
.append("_")
.append(method.getName())
.append("_")
.append(StringUtils.arrayToDelimitedString(objects, "_"));
return stringBuffer.toString();
}
}
3、在类上使用,访问类所有的方法都缓存
import com.pingan.domain.Student;
import com.pingan.mapper.StudentMapper;
import com.pingan.service.StudentService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 在类上加 @Cacheable 代表类下面所有的方法都缓存,cacheNames随便起,keyGenerator为自定义缓存key的bean
@Service("studentService")
@Cacheable(cacheNames = "StudentServiceCache",keyGenerator = "myKeyGenerator")
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public Student queryById(Integer id) {
return this.studentMapper.queryById(id);
}
}
在方法上使用,访问此方法才会缓存
@Cacheable(cacheNames = "StudentServiceCache",keyGenerator = "myKeyGenerator")
public Student queryById(Integer id) {
return this.studentMapper.queryById(id);
}
4、在更新和插入的方法上加上 @CacheEvict 清空缓存
@CacheEvict(cacheNames = "StudentServiceCache",allEntries = true)
public Student insert(Student student) {
this.studentMapper.insert(student);
return student;
}