dev add geo country service
Test Workflow / test (push) Successful in 3s

This commit is contained in:
vladp
2026-04-15 10:10:46 +07:00
parent 684888aa2c
commit 11ee4e18ed
@@ -14,8 +14,8 @@ import java.util.concurrent.ConcurrentHashMap;
@Service
@Slf4j
public class GeoCountryService {
private DatabaseReader dbReader;
private DatabaseReader dbReader;
private final Map<String, String> cache = new ConcurrentHashMap<>();
@PostConstruct
@@ -23,19 +23,18 @@ public class GeoCountryService {
try {
var resource = new ClassPathResource("geo/GeoLite2-Country.mmdb");
this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build();
log.info("Geo DB loaded");
} catch (Exception e) {
log.error("Failed to load Geo DB", e);
throw new RuntimeException(e);
}
}
public String getCountry(String url) {
if (url == null || url.isBlank()) {
public String getCountry(String input) {
if (input == null || input.isBlank()) {
return null;
}
String host = extractHost(url);
String host = extractHost(input);
if (cache.containsKey(host)) {
return cache.get(host);
}
@@ -45,18 +44,21 @@ public class GeoCountryService {
CountryResponse response = dbReader.country(ip);
String country = response.getCountry().getIsoCode();
cache.put(host, country);
cache.put(host, country != null ? country : "");
log.debug("{} → {}", host, country);
return country;
} catch (Exception e) {
log.debug("Cannot determine country for: {}", host);
cache.put(host, null);
cache.put(host, "");
return null;
}
}
private String extractHost(String url) {
String cleaned = url.replaceFirst("^https?://", "");
return cleaned.split("[/:]")[0];
private String extractHost(String input) {
String s = input.replaceFirst("^https?://", "");
s = s.split("/")[0];
s = s.split(":")[0];
return s;
}
}