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 @Service
@Slf4j @Slf4j
public class GeoCountryService { public class GeoCountryService {
private DatabaseReader dbReader;
private DatabaseReader dbReader;
private final Map<String, String> cache = new ConcurrentHashMap<>(); private final Map<String, String> cache = new ConcurrentHashMap<>();
@PostConstruct @PostConstruct
@@ -23,19 +23,18 @@ public class GeoCountryService {
try { try {
var resource = new ClassPathResource("geo/GeoLite2-Country.mmdb"); var resource = new ClassPathResource("geo/GeoLite2-Country.mmdb");
this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build(); this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build();
log.info("Geo DB loaded");
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to load Geo DB", e); log.error("Failed to load Geo DB", e);
throw new RuntimeException(e);
} }
} }
public String getCountry(String url) { public String getCountry(String input) {
if (url == null || url.isBlank()) { if (input == null || input.isBlank()) {
return null; return null;
} }
String host = extractHost(url); String host = extractHost(input);
if (cache.containsKey(host)) { if (cache.containsKey(host)) {
return cache.get(host); return cache.get(host);
} }
@@ -45,18 +44,21 @@ public class GeoCountryService {
CountryResponse response = dbReader.country(ip); CountryResponse response = dbReader.country(ip);
String country = response.getCountry().getIsoCode(); String country = response.getCountry().getIsoCode();
cache.put(host, country); cache.put(host, country != null ? country : "");
log.debug("{} → {}", host, country);
return country; return country;
} catch (Exception e) { } catch (Exception e) {
log.debug("Cannot determine country for: {}", host); cache.put(host, "");
cache.put(host, null);
return null; return null;
} }
} }
private String extractHost(String url) { private String extractHost(String input) {
String cleaned = url.replaceFirst("^https?://", ""); String s = input.replaceFirst("^https?://", "");
return cleaned.split("[/:]")[0]; s = s.split("/")[0];
s = s.split(":")[0];
return s;
} }
} }