|
|
package com.monitor.cmdb.ctrl;
|
|
|
|
|
|
import com.monitor.cmdb.service.IHostInfoService;
|
|
|
import org.apache.commons.lang.StringUtils;
|
|
|
import org.slf4j.Logger;
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.stereotype.Controller;
|
|
|
import org.springframework.web.bind.annotation.RequestBody;
|
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
|
import org.springframework.web.bind.annotation.ResponseBody;
|
|
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
|
|
|
/**
|
|
|
* Created by craig.qin on 2017/11/1.
|
|
|
*/
|
|
|
@Controller
|
|
|
@RequestMapping("/cmdb")
|
|
|
public class CmdbApiCtrl {
|
|
|
|
|
|
Logger log = LoggerFactory.getLogger(CmdbApiCtrl.class);
|
|
|
|
|
|
@Autowired
|
|
|
IHostInfoService hostInfoService;
|
|
|
|
|
|
/**
|
|
|
* 根据提供的tags标签查询host。返回json串
|
|
|
*/
|
|
|
@RequestMapping("/api")
|
|
|
@ResponseBody
|
|
|
public String api(HttpServletRequest request,@RequestBody String content) {
|
|
|
String ip=getIpAddr(request);
|
|
|
return hostInfoService.getHostInfoJson(ip, content);
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
* 获取访问者IP
|
|
|
*
|
|
|
* 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。
|
|
|
*
|
|
|
* 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割),
|
|
|
* 如果还不存在则调用Request .getRemoteAddr()。
|
|
|
*
|
|
|
* @param request
|
|
|
* @return
|
|
|
*/
|
|
|
private String getIpAddr(HttpServletRequest request) {
|
|
|
String ip = request.getHeader("X-Real-IP");
|
|
|
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
|
|
|
return ip;
|
|
|
}
|
|
|
ip = request.getHeader("X-Forwarded-For");
|
|
|
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
|
|
|
// 多次反向代理后会有多个IP值,第一个为真实IP。
|
|
|
int index = ip.indexOf(',');
|
|
|
if (index != -1) {
|
|
|
return ip.substring(0, index);
|
|
|
} else {
|
|
|
return ip;
|
|
|
}
|
|
|
} else {
|
|
|
return request.getRemoteAddr();
|
|
|
}
|
|
|
}
|
|
|
} |
...
|
...
|
|