获取真实IP
在开发时候获取的是当前局域网ip,当把项目部署到服务器上的时候获取的就是真实ip
/**
* 获取访问者真实IP地址
*/
public String getIpAddr(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
// 根据网卡取本机配置的IP
try {
ipAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length()
if (ipAddress != null && ipAddress.length() > 15) {
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
根据ip获取当前定位
需要传入真实ip作为参数
/**
* 根据当前登录人的ip解析出登录地址
* 调用的是高德接口
* @return
* @throws JSONException
* @throws IOException
*/
public String guideGetCityCode(HttpServletRequest request) throws JSONException {
//调用获取真实ip方法
String ip = getIpAddr(request);
//高德key 这个key需要去高德开发平台自己申请,我是申请好了写在了配置类中
String key = commonConfig.getGao_de_key();
String ipUrl = "http://restapi.amap.com/v3/ip?ip=" + ip + "&key=" + key + "";
// restTemplate是springboot自带的发送请求封装好的模板,需要注入,这个注入有一点点坑的,慢慢踩吧
// JSONObject是alibaba的
JSONObject json = restTemplate.getForObject(ipUrl, JSONObject.class);
String province = (String) json.get("province");
String city = (String) json.get("city");
return province + city;
}
接口限制用户一分钟内只能请求一次短信发送
/**
* 接口限制用户一分钟内只能请求一次短信发送
* 如果这个用户连续发了10条的话
* 就冻结这个IP 10分钟内不让发送
* 依赖与redis和session
*/
public Boolean getSendSmsLimit(HttpServletRequest request, String mobile, String TemplateCode, String yzm) {
// 获取请求接口人的ip地址
String ipKey = commonConfig.getSms_visit_limit() + getIpAddr(request) + "_" + mobile;
log.info("当前访问ip--------->{}", ipKey);
/**
* 去redis中查看这个ip地址剩余时间
* >0 证明时间已经过去一分钟,可以发送
*/
if (redisUtil.ttl(ipKey) > 0) {
// 不可以发送
throw new BusinessException(ResponseEnum.TIME_LIMIT_SMS);
}
HttpSession session = request.getSession();
Integer index = (Integer) session.getAttribute("index");
if (commonConfig.getSms_visit_num().equals(index)) {
redisUtil.set(ipKey, 1, 600L);
session.removeAttribute("index");
return false;
}
if (index == null) {
index = 1;
} else {
index += 1;
}
// 可以发送
if (smsUtils.sendSms(mobile, TemplateCode, yzm)) {
session.setAttribute("index", index);
redisUtil.set(ipKey, 1, 60L);
return true;
}
return false;
}