1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| @Override public ResponseResult getWeatherNow(String location, String lang, String unit) { String cityName = resolveCityName(location); String locationId = CityLocationUtils.getLocationIdByCityName(cityName); if (!StringUtils.hasText(locationId)) { log.warn("城市名称无法映射到Location_ID: cityName={}", cityName); return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), "获取天气信息异常:无法获取“ " + cityName + " ”城市的天气信息"); }
lang = StringUtils.hasText(lang) ? lang : "zh"; unit = StringUtils.hasText(unit) ? unit : "m";
String cacheKey = RedisKeyConstants.WEATHER_NOW_KEY_PREFIX + locationId + ":" + lang + ":" + unit; WeatherNowVo cachedWeather = redisCache.getCacheObject(cacheKey); if (cachedWeather != null) { log.info("从缓存获取天气数据: locationId={}", locationId); return ResponseResult.okResult(cachedWeather); }
try { ResponseEntity<QWeatherResponseVo<WeatherNowVo>> response = callWeatherApi(locationId, lang, unit); return handleWeatherResponse(response, cacheKey, locationId); } catch (Exception e) { log.error("调用和风天气API异常: locationId={}, cityName={}, error={}", locationId, cityName, e.getMessage(), e); return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), "获取天气信息异常:无法获取“ " + cityName + " ”的天气信息"); } }
private String resolveCityNameByIp() { try { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); String clientIp = IpUtils.getIpAddr(request); log.info("客户端IP地址: {}", clientIp);
String cityName = IpLocationUtils.getCityNameByIp(clientIp); if (StringUtils.hasText(cityName)) { log.info("根据IP解析的城市: {}", cityName); return cityName; }
log.warn("IP地址解析城市失败"); } else { log.warn("无法获取请求上下文"); } } catch (Exception e) { log.error("IP地址解析异常: {}", e.getMessage(), e); }
return null; }
private String resolveCityName(String location) { if (StringUtils.hasText(location)) { String cityName = location.trim(); log.info("使用传入的城市参数: {}", cityName); return cityName; }
return resolveCityNameByIp(); }
|