Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Java reader for the MaxMind DB format

License

NotificationsYou must be signed in to change notification settings

maxmind/MaxMind-DB-Reader-java

Repository files navigation

Description

This is the Java API for reading MaxMind DB files. MaxMind DB is a binary fileformat that stores data indexed by IP address subnets (IPv4 or IPv6).

Installation

Maven

We recommend installing this package withMaven.To do this, add the dependency to your pom.xml:

    <dependency>        <groupId>com.maxmind.db</groupId>        <artifactId>maxmind-db</artifactId>        <version>3.2.0</version>    </dependency>

Gradle

Add the following to yourbuild.gradle file:

repositories {    mavenCentral()}dependencies {    compile 'com.maxmind.db:maxmind-db:3.2.0'}

Usage

Note: For accessing MaxMind GeoIP2 databases, we generally recommend usingtheGeoIP2 Java API rather than usingthis package directly.

To use the API, you must first create aReader object. The constructor forthe reader object takes aFile representing your MaxMind DB. Optionally youmay pass a second parameter with aFileMode with a value ofMEMORY_MAP orMEMORY. The default mode isMEMORY_MAP, which maps the file to virtualmemory. This often provides performance comparable to loading the file intoreal memory withMEMORY.

To look up an IP address, pass the address as anInetAddress to thegetmethod onReader, along with the class of the object you want todeserialize into. This method will create an instance of the class andpopulate it. See examples below.

We recommend reusing theReader object rather than creating a new one foreach lookup. The creation of this object is relatively expensive as it mustread in metadata for the file.

Example

importcom.maxmind.db.MaxMindDbConstructor;importcom.maxmind.db.MaxMindDbParameter;importcom.maxmind.db.Reader;importcom.maxmind.db.DatabaseRecord;importjava.io.File;importjava.io.IOException;importjava.net.InetAddress;publicclassLookup {publicstaticvoidmain(String[]args)throwsIOException {Filedatabase =newFile("/path/to/database/GeoIP2-City.mmdb");try (Readerreader =newReader(database)) {InetAddressaddress =InetAddress.getByName("24.24.24.24");// get() returns just the data for the associated recordLookupResultresult =reader.get(address,LookupResult.class);System.out.println(result.getCountry().getIsoCode());// getRecord() returns a DatabaseRecord class that contains both// the data for the record and associated metadata.DatabaseRecord<LookupResult>record                =reader.getRecord(address,LookupResult.class);System.out.println(record.getData().getCountry().getIsoCode());System.out.println(record.getNetwork());        }    }publicstaticclassLookupResult {privatefinalCountrycountry;@MaxMindDbConstructorpublicLookupResult (@MaxMindDbParameter(name="country")Countrycountry        ) {this.country =country;        }publicCountrygetCountry() {returnthis.country;        }    }publicstaticclassCountry {privatefinalStringisoCode;@MaxMindDbConstructorpublicCountry (@MaxMindDbParameter(name="iso_code")StringisoCode        ) {this.isoCode =isoCode;        }publicStringgetIsoCode() {returnthis.isoCode;        }    }}

Constructor and parameter selection

  • Preferred: annotate a constructor with@MaxMindDbConstructor and itsparameters with@MaxMindDbParameter(name = "...").
  • Records: if no constructor is annotated, the canonical record constructor isused automatically. Record component names are used as field names.
  • Classes with a single public constructor: if no constructor is annotated,that constructor is used automatically.
  • Unannotated parameters: when a parameter is not annotated, the reader fallsback to the parameter name. For records, this is the component name; forclasses, this is the Java parameter name. To use Java parameter names atruntime, compile your model classes with the-parameters flag (Maven:maven-compiler-plugin with<parameters>true</parameters>).If Java parameter names are unavailable (no-parameters) and there is no@MaxMindDbParameter annotation, the reader throws aParameterNotFoundException with guidance.

Defaults for missing values

  • Provide a default with@MaxMindDbParameter(name = "...", useDefault = true, defaultValue = "...").

  • Supports primitives, boxed types, andString. IfdefaultValue is emptyanduseDefault is true, Java defaults are used (0, false, 0.0, emptystring).

  • Example:

    @MaxMindDbConstructorExample(@MaxMindDbParameter(name ="count",useDefault =true,defaultValue ="0")intcount,@MaxMindDbParameter(name ="enabled",useDefault =true,defaultValue ="true"    )booleanenabled) { }

Lookup context injection

  • Use@MaxMindDbIpAddress to inject the IP address being decoded.Supported parameter types areInetAddress andString.
  • Use@MaxMindDbNetwork to inject the network of the resulting record.Supported parameter types areNetwork andString.
  • Context annotations cannot be combined with@MaxMindDbParameter on the sameconstructor argument. Values are populated for every lookup without beingcached between different IPs.

Custom deserialization

  • Use@MaxMindDbCreator to mark a static factory method or constructor thatshould be used for custom deserialization of a type from a MaxMind DB file.

  • This annotation is similar to Jackson's@JsonCreator and is useful fortypes that need custom deserialization logic, such as enums with non-standardstring representations or types that require special initialization.

  • The annotation can be applied to both constructors and static factory methods.

  • Example with an enum:

    publicenumConnectionType {DIALUP("Dialup"),CABLE_DSL("Cable/DSL");privatefinalStringname;ConnectionType(Stringname) {this.name =name;    }@MaxMindDbCreatorpublicstaticConnectionTypefromString(Strings) {returnswitch (s) {case"Dialup" ->DIALUP;case"Cable/DSL" ->CABLE_DSL;default ->null;        };    }}

You can also use the reader object to iterate over the database.Thereader.networks() andreader.networksWithin() methods canbe used for this purpose.

Readerreader =newReader(file);Networksnetworks =reader.networks(Map.class);while(networks.hasNext()) {DatabaseRecord<Map<String,String>>iteration =networks.next();// Get the data.Map<String,String>data =iteration.getData();// The IP AddressInetAddressipAddress =InetAddress.getByName(data.get("ip"));// ...}

Caching

The database API supports pluggable caching (by default, no caching isperformed). A simple implementation is provided bycom.maxmind.db.CHMCache.Using this cache, lookup performance is significantly improved at the cost ofa small (~2MB) memory overhead.

Usage:

Readerreader =newReader(database,newCHMCache());

Please note that the cache will hold references to the objects createdduring the lookup. If you mutate the objects, the mutated objects will bereturned from the cache on subsequent lookups.

Multi-Threaded Use

This API fully supports use in multi-threaded applications. In suchapplications, we suggest creating oneReader object and sharing that amongthreads.

Common Problems

File Lock on Windows

By default, this API uses theMEMORY_MAP mode, which memory maps the file.On Windows, this may create an exclusive lock on the file that prevents itfrom being renamed or deleted. Due to the implementation of memory mapping inJava, this lock will not be released when theDatabaseReader is closed; itwill only be released when the object and theMappedByteBuffer it uses aregarbage collected. Older JVM versions may also not release the lock on exit.

To work around this problem, use theMEMORY mode or try upgrading your JVMversion. You may also callSystem.gc() after dereferencing theDatabaseReader object to encourage the JVM to garbage collect sooner.

Packaging Database in a JAR

If you are packaging the database file as a resource in a JAR file usingMaven, you mustdisable binary file filtering.Failure to do so will result inInvalidDatabaseException exceptions beingthrown when querying the database.

Format

The MaxMind DB format is an open format for quickly mapping IP addresses torecords. Thespecificationis available, as is ourPerl writer for theformat.

Bug Tracker

Please report all issues with this code using theGitHub issuetracker.

If you are having an issue with a MaxMind database or service that is notspecific to this reader, pleasecontact MaxMind support.

Requirements

This API requires Java 17 or greater.

Contributing

Patches and pull requests are encouraged. Please include unit tests wheneverpossible.

Versioning

The MaxMind DB Reader API usesSemantic Versioning.

Copyright and License

This software is Copyright (c) 2014-2025 by MaxMind, Inc.

This is free software, licensed under the Apache License, Version 2.0.

Packages

No packages published

Contributors28


[8]ページ先頭

©2009-2025 Movatter.jp