根据ip获取国家

 

<!-- https://mvnrepository.com/artifact/com.maxmind.geoip/geoip-api -->
        <dependency>
            <groupId>com.maxmind.geoip</groupId>
            <artifactId>geoip-api</artifactId>
            <version>1.3.0</version>
        </dependency>

Country_GeoIP.dat在博客文件管理列表中

 

package com.onloon.website.analytics.common.utils;

import java.io.IOException;
import java.net.InetAddress;

import com.maxmind.geoip.Location;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import com.maxmind.geoip.Country;
import com.maxmind.geoip.LookupService;
import com.onloon.website.analytics.common.exception.BusinessException;

public class GeoIpUtil {
    
    private static final String COUNTRY_DATA_PATH="/ipdb/Country_GeoIP.dat";
    private static final String CITY_DATA_PATH="/ipdb/GeoLiteCity.dat";

    private static  LookupService lookupService;
    private static  LookupService lookupCityService;

    /**
     * 查询指定ip的国家英文名称
     * 
     * @author pengfeng(彭锋)
     * @time 下午3:44:00  
     * @param ip
     * @return
     */
    public static String getCountryEnName(String ip) {
        if(lookupService==null) {
            load();
        }
        if(lookupService==null) {
            return null;
        }
        Country country=lookupService.getCountry(ip);
        if(country==null||StringUtils.isBlank(country.getName())) {
            return null;
        }
        return country.getName();
    }

    /**
     * 根据IP获取位置信息
     * @param ip
     * @return
     */
    public static Location getLocatinInfo(String ip){
        if(lookupCityService==null) {
            loadCity();
        }
        if(lookupCityService==null) {
            return null;
        }
        return lookupCityService.getLocation(ip);
    }
    
    //加载数据文件
    private static synchronized void  load() {
        if(lookupService!=null) {
            return;
        }
        ClassPathResource resource = new ClassPathResource(COUNTRY_DATA_PATH);
        try {
            lookupService=new LookupService(resource.getFile());
        } catch (IOException e) {
            throw new BusinessException();
        }
    }

    //加载数据文件
    private static synchronized void  loadCity() {
        if(lookupCityService!=null) {
            return;
        }
        ClassPathResource resource = new ClassPathResource(CITY_DATA_PATH);
        try {
            lookupCityService=new LookupService(resource.getFile());
        } catch (IOException e) {
            throw new BusinessException();
        }
    }
}

 

转载于:https://www.cnblogs.com/wanhua-wu/p/9327334.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值