Java IP 地址访问次数统计优化和JSON转换问题解决

问题1:IP访问次数统计有误,无法正确累加次数

原因: 由于Map<String, Integer> ipcount定义在方法内部,每次请求都会重新创建,导致无法累加次数。

解决方案:ipcount定义为成员变量,避免每次请求都重新创建,确保能够正确累加次数。

完善代码:

public class XxxServiceImpl implements XxxService {

    //IP访问次数
    private Map<String, Integer> ipcount = new HashMap<>();

    @Override
    public TableDataInfo<IpAddressesVo> queryPageList(IpAddressesBo bo, PageQuery pageQuery, HttpServletRequest request) {
        String ipAddr = RegionUtil.getRegion(IpUtils.getIpAddr(request));
        //ip归属地
        String location = AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(request));
        if (StringUtils.isNotEmpty(ipAddr)) {
            if (ipcount.containsKey(ipAddr)) {
                //ip存在累计次数
                Integer cnt = ipcount.get(ipAddr);
                ipcount.put(ipAddr, cnt + 1);
            } else {//ip不存在,第一次
                ipcount.put(ipAddr, 1);
            }
        }
        //其他代码不变
        //...
    }
}

问题2:IpAddressesVo对象为空时,无法正确转换为JSON字符串

原因: 由于判断条件为ipAddressesVo!=null,而ipAddressesVo默认情况下为空,导致无法进行JSON转换。

解决方案: 将判断条件改为ipAddresses != null,并且将JSON字符串赋值给ipAddressesVojson属性。

完善代码:

IpAddressesVo ipAddressesVo = new IpAddressesVo();
if (ipAddresses != null) {
    BeanUtil.copyProperties(ipAddresses, ipAddressesVo);
    ipAddressesVo.setOs('windows');//操作系统
    ipAddressesVo.setLocation(location);//归属地
    ipAddressesVo.setAccessCount(ipcount.get(ipAddr));//访问次数
    ipAddressesVo.setUpdateTime(new Date());//访问时间
    ipAddressesVo.setJson(JSON.toJSONString(ipAddressesVo));//JSON字符串
}

通过以上优化,代码能够正确统计IP访问次数并转换为JSON字符串,提高了代码的健壮性和可读性。

Java IP 地址访问次数统计优化和JSON转换问题解决

原文地址: https://www.cveoy.top/t/topic/mQpe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录