1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| public class GeoIPUtil { private final DatabaseReader reader;
public GeoIPUtil(String dbPath, boolean loadToMemory) { try { System.out.println("--------------- load GEO-IP Data ---------------"); Resource resource; if (dbPath.startsWith("classpath:")) { resource = new ClassPathResource(dbPath.substring("classpath:".length())); } else { resource = new FileSystemResource(dbPath); } DatabaseReader.Builder builder = new DatabaseReader.Builder(resource.getFile()); if (loadToMemory) { builder.fileMode(com.maxmind.db.Reader.FileMode.MEMORY); } else { builder.fileMode(com.maxmind.db.Reader.FileMode.MEMORY_MAPPED); } this.reader = builder.build(); System.out.println("--------------- build GEO-IP Data --------------"); } catch (Exception e) { throw new RuntimeException("Failed to initialize GeoIP database", e); } }
public GeoIPInfo getGeoIPInfo(String ip) { return getGeoIPInfoOptional(ip).orElse(null); }
public Optional<GeoIPInfo> getGeoIPInfoOptional(String ip) { if (!StringUtils.hasText(ip)) { return Optional.empty(); } try { CityResponse response = reader.city(InetAddress.getByName(ip)); return Optional.of(new GeoIPInfo( response.getCountry().getIsoCode(), response.getCountry().getName(), response.getCity().getName(), response.getLocation().getLatitude(), response.getLocation().getLongitude(), response.getLocation().getTimeZone() )); } catch (Exception e) { return Optional.empty(); } } }
|