Я хочу реализовать структуру кеша в первый раз. У меня есть таблица. Эта таблица обновляется каждые 2 мин. Поэтому я хочу сохранить данные таблицы после отправки первого запроса, и я хочу очистить кеш через 2 мин. .
Мой код
@Service
public class CacheTesting{
public static final String REFRESH_CACHE_METHOD_NAME = "refreshParameterCache";
public static long DEFAULT_CACHE_REFRESH_INTERVAL = 120000;
public Date lastFetchDate = null;
private List<Student> studentList = new ArrayList<Student>();
private Map<Integer, Integer> studentMap = new HashMap<Integer, Integer>();
private long timeout;
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@Autowired
private StudentRepository studentRepository;
public Integer findStudentAgeByStudentId(Integer studentId) {
this.checkParameterCache();
for (Iterator<Student> iterator = studentList.iterator(); iterator.hasNext(); ) {
Student studentMap = (Student) iterator.next();
if (studentMap.getStudentId() == studentId) {
return studentMap.getStudentAge();
}
}
return null;
}
public List<Student> listParameters() {
return studentRepository.findAll();
}
private void checkParameterCache() {
if (this.isParameterCacheExpired()) {
synchronized (this.studentList) {
if (this.studentList == null || this.studentList.size() == 0) {
refreshParameterCache();
} else if (this.isParameterCacheExpired()) {
CacheManager cacheManager = new CacheManager(this, REFRESH_CACHE_METHOD_NAME);
(new Thread(cacheManager)).start();
this.lastFetchDate = new Date();
}
}
}
}
private boolean isParameterCacheExpired() {
long timeout = 120000;
return lastFetchDate == null || (lastFetchDate.getTime() + (timeout)) < new Date().getTime();
}
public void refreshParameterCache() {
this.studentList = this.listParameters();
if (studentList != null && studentList.size() > 0) {
this.studentMap.clear();
for (Iterator iterator = studentList.iterator(); iterator.hasNext(); ) {
Student student= (Student) iterator.next();
this.studentMap.put(student.getStudentId(), student.getAge());
}
lastFetchDate = new Date();
}
}
}
Моя проблема: всякий раз, когда я вызываю findStudentAgeByStudentId
метод, studentList не пуст. Как я могу очистить данные кеша? Также как я могу найти свои данные кеша ?