Springboot整合ip2Region实现区域解析

简介

  1. 本文介绍的是如何通过ip地址解析出ip对应区域信息;
  2. 通过 Spring boot 整合 ip2Region 实现;

项目结构

项目结构

核心代码

  • 将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;
    }

效果

效果


代码仓地址

代码仓地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值