简介
- 本文介绍的是如何通过ip地址解析出ip对应区域信息;
- 通过 Spring boot 整合 ip2Region 实现;
项目结构

核心代码
public Searcher autoIp2regionSearcher(@Autowired Ip2RegionProperties properties) {
ClassPathResource resource = new ClassPathResource(properties.getDbFile());
try (InputStream inputStream = resource.getInputStream()) {
byte[] dbBytes = IOUtils.toByteArray(inputStream);
log.info("autoIp2regionSearcher: dbFilePath = {}", properties.getDbFile());
return Searcher.newWithBuffer(dbBytes);
} catch (FileNotFoundException fileNotFoundException) {
log.error("autoIp2regionSearcher can not find db file in the path [{}], error-trace:", properties.getDbFile()
, fileNotFoundException);
} catch (IOException ioException) {
log.error("autoIp2regionSearcher createTempFile fail: [{}], error-trace:", properties.getDbFile(), ioException);
throw new RuntimeException(ioException);
}
return null;
}
工具类调用
public IpRegionDTO searchParseDto(String ip) {
String region;
try {
region = searcher.search(ip);
} catch (Exception e) {
throw new RuntimeException(e);
}
String[] parts = region.split("\\|");
IpRegionDTO dto = new IpRegionDTO();
dto.setCountry("0".equals(parts[0]) ? null : parts[0]);
dto.setProvince("0".equals(parts[2]) ? null : parts[2]);
dto.setCity("0".equals(parts[3]) ? null : parts[3]);
dto.setIsp("0".equals(parts[4]) ? null : parts[4]);
return dto;
}
效果

代码仓地址
代码仓地址