Java获取 IP 详细信息、经纬度

可以自己搭建,也可以直接使用现成的请求链接,每个月月初更新 ip 库

     获取城市信息:http://ip.guoxinqi.cn/city/47.96.229.169

     获取IP经纬度信息:http://ip.guoxinqi.cn/position/47.96.229.169

自己搭建:

可用于拦截操作、获取 IP 详细信息、及黑名单操作获取。

拦截操作: MvcConfigurer中addInterceptors中指定拦截方法(/** 全部请求拦截),在 FilterHandler 的 preHandle 方法可做拦截后的操作(例:黑名单拦截、请求拦截)

IP 详细信息获取: 使用 InterceptServer 方法获取 ip 的详细信息,可获取国家、省份、城市、经纬度 等。(结合拦截操作可实现黑名单拦截、白名单放行、拦截指定国家、省份、城市的拦截操作)

项目地址及介绍:https://gitee.com/qq1319426493/IP-Intercept

软件架构

使用 SpringBoot ,GeoLite2City

 

新建项目(IP-Intercept):

1、pom.xml 导包


  4.0.0
  

	com.zwsd
    IP-Intercept
	1.0

	IP-Intercept
	http://www.example.com
  
	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.4.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-tomcat
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		 
	 	
			org.springframework.boot
			spring-boot-starter-redis
			1.4.7.RELEASE
		
		
		
		
		    com.maxmind.geoip2
		    geoip2
		    2.9.0
		
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

	
		
			spring-snapshots
			Spring Snapshots
			https://repo.spring.io/snapshot
			
				true
			
		
		
			spring-milestones
			Spring Milestones
			https://repo.spring.io/milestone
			
				false
			
		
	

	
		
			spring-snapshots
			Spring Snapshots
			https://repo.spring.io/snapshot
			
				true
			
		
		
			spring-milestones
			Spring Milestones
			https://repo.spring.io/milestone
			
				false
			
		
	

2、新建Applocation启动文件

package com.gitee.Intercept;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class InterceptApplication {

	public static void main(String[] args) {
		SpringApplication.run(InterceptApplication.class, args);
	}
	
}

3、新建 FilterHandler 继承  HandlerInterceptor

package com.gitee.Intercept.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class FilterHandler implements HandlerInterceptor{

	/*
	 * 在调用controller方法之前会调用此方法,返回true会正常执行程序,返回false折中断执行,
	 * 可以做拦截操作,比如黑名单之类的
	 * 
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	   

}

4、新建 视图管理器 MvcConfigurer  继承 WebMvcConfigurer

package com.gitee.Intercept.filter;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfigurer  implements WebMvcConfigurer{


	/**
	 * 拦截方法(/** 拦截所有)
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new FilterHandler()).addPathPatterns("/**");
		
	}

	

}

5、封装 获取 ip详细信息 InterceptServer

package com.gitee.Intercept.server;

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

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;

@Service
public class InterceptServer {
	
	private static Logger logger = LoggerFactory.getLogger(InterceptServer.class);


	private static CityResponse city ;

	//@Value("${file.GeoLite2City}")
	private static final String filePath = "/geoLite2City/GeoLite2-City.mmdb";

	private static DatabaseReader reader;
	

	

	@PostConstruct
	public void init() {
		try {
			File file = new ClassPathResource(filePath).getFile();
			reader = new DatabaseReader.Builder(file).build();

		} catch (Exception e) {
			logger.error("IP init failed :"+e.getMessage() , e);
		}
	}
	
	public CityResponse getCity(String ipAddress) {
		getResponse(ipAddress);
		return city;
		
	}

	private CityResponse getResponse(String ipAddress) {

		if(StringUtils.isEmpty(ipAddress)) {
			 throw new NullPointerException();
		}
		try {

			InetAddress address = InetAddress.getByName(ipAddress);
			this.city = reader.city(address);

		} catch (UnknownHostException e) {

			logger.error("DNS oarsing failed : " +e.getMessage(),e);

		} catch (IOException e) {

			logger.error("not exist file : "+e.getMessage(),e);

		} catch (GeoIp2Exception e) {

			logger.error("GeoIp2 faild : "+e.getMessage(),e);

		}

		return null;


	}

}

5、新建application.yml 文件,空的

6、下载GeoLite2-City,地址 https://dev.maxmind.com/geoip/geoip2/geolite2/

Java获取 IP 详细信息、经纬度_第1张图片

7、新建IndexController

package com.gitee.Intercept.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gitee.Intercept.server.InterceptServer;
import com.maxmind.geoip2.model.CityResponse;

@Controller
public class IndexController {

	@Autowired
	private InterceptServer interceptServer;
	
	@GetMapping("/a//{ip}")
	@ResponseBody
	public String test(@PathVariable("ip")  String ip) {

		CityResponse country = interceptServer.getCity(ip);
		
	return String.valueOf(country);	
	}
}

8、启动,访问路径http://localhost:8080/a/ip地址   

如图所示

Java获取 IP 详细信息、经纬度_第2张图片

你可能感兴趣的:(Java基础,架构)