Skip to content

Commit

Permalink
refactor(MemCachedSearchEmployee)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chamber6821 committed Apr 18, 2024
1 parent 9523674 commit a314987
Showing 1 changed file with 16 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.example.jonebook.services.search;

import com.example.jonebook.entities.Employee;
import com.example.jonebook.services.dto.EmployeeCriteria;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.domain.Page;
Expand All @@ -8,26 +10,23 @@
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import com.example.jonebook.entities.Employee;
import com.example.jonebook.services.dto.EmployeeCriteria;

@Service
public class MemCachedSearchEmployee implements SearchEmployee {

private final SearchEmployee origin;
private final Map<Pair<EmployeeCriteria, Pageable>, Page<Employee>> cache = new HashMap<>();
private final SearchEmployee origin;
private final Map<Pair<EmployeeCriteria, Pageable>, Page<Employee>> cache =
new HashMap<>();

public MemCachedSearchEmployee(SearchEmployee origin) {
this.origin = origin;
}
public MemCachedSearchEmployee(SearchEmployee origin) {
this.origin = origin;
}

@Override
public Page<Employee> search(@NonNull EmployeeCriteria criteria, @NonNull Pageable pageable) {
if (cache.size() > 10000)
cache.keySet().stream().findFirst().ifPresent(x -> cache.remove(x));
var key = Pair.of(criteria, pageable);
if (!cache.containsKey(key))
cache.put(key, origin.search(criteria, pageable));
return cache.get(key);
}
@Override
public Page<Employee> search(@NonNull EmployeeCriteria criteria,
@NonNull Pageable pageable) {
if (cache.size() > 10000)
cache.keySet().stream().findFirst().ifPresent(cache::remove);
var key = Pair.of(criteria, pageable);
return cache.computeIfAbsent(key, x -> origin.search(criteria, pageable));
}
}

0 comments on commit a314987

Please sign in to comment.