feat(weather): 新增多端天气接口与和风天气代理

- 新增 /api/v1/sn/weather 与 /api/v1/client/weather 的 current、hourly、daily 端点,按区县 adCode 查询
- 新增 QWeatherClient 与 WeatherService,实况缓存 30 分钟、逐小时到整点刷新、逐天到当地午夜刷新,上游失败返回 stale 旧缓存
- 新增 NearbyWeatherController/Service,提供分钟级降水、天气预警与空气质量接口
- 打包大陆行政区划表 mainland-areas.tsv,补充 docs/weather-api.md 与时间戳单测
This commit is contained in:
tongtong committed 2026-11-29 23:37:10 +08:00
1 parent 221308f936
commit 966aa1dfa9
9 files changed
+3975

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
# 多端天气接口
设备端与家属端共用同一套 JSON 数据。客户端调用项目后端的 HTTPS 域名。
| 调用方 | 接口前缀 | 鉴权 |
|---|---|---|
| ElderlyDialer | `/api/v1/sn/weather` | 使用现有设备签名请求封装 |
| Flutter、iOS、小程序、鸿蒙、H5 | `/api/v1/client/weather` | 家属端访问令牌 `Authorization: Bearer <accessToken>` |
天气类型由三个固定路由指定。请求传入六位大陆行政区划码 `adCode`,可选语言 `lang` 支持 `zh`(默认)、`zh-hant`、`en`。例如家属端实时天气使用 `GET /api/v1/client/weather/current?adCode=110108`。地区名为区划表里的中文名称。
| GET 路径后缀 | 返回 | 缓存新鲜期 |
|---|---|---|
| `/current?adCode=110108` | 一条实况 | 30 分钟 |
| `/hourly?adCode=110108` | 未来最多 24 小时 | 最长 60 分钟,到整点刷新 |
| `/daily?adCode=110108` | 未来最多 10 天 | 最长 6 小时,到大陆当地午夜刷新 |
使用项目标准 `Result` 响应。成功时 `data` 包含以下字段。
- `adCode`、`areaName`、`timeZone` 标识区县和当地时区。
- `fetchedAt` 为服务端成功获取时间,UTC ISO 8601 字符串。实况的观测时间使用 `periods[0].time`。
- `stale` 表示刷新期间或上游失败时返回的旧缓存。界面显示数据时间,切换地区时按新地区查缓存。
- `attributions` 是上游数据归因链接,界面随天气数据展示。
- `periods` 为数据列表。`time` 和 `endTime` 是 UTC ISO 8601 字符串,`localDate` 是当地日期。天气现象取 `condition.code` 和 `condition.text`,逐天数据同时提供 `nightCondition`。温度字段使用摄氏度,`humidityPercent` 为 0–100。不同数据类型下不适用的字段可能为 null。
首页优先请求实况,详情页按需请求逐小时和逐天。小程序发布时将项目后端的 HTTPS 域名加入 request 合法域名。H5 可使用项目现有 API 网关和家属端令牌。各端可以沿用现有网络库和鉴权拦截器。
## 后端配置
| 环境变量 | 含义 |
|---|---|
| `TTSTD_WEATHER_HOST` | 和风专属 API Host,仅域名 |
| `TTSTD_WEATHER_PROJECT_ID` | 和风项目 ID |
| `TTSTD_WEATHER_KEY_ID` | JWT 凭据 ID |
| `TTSTD_WEATHER_PRIVATE_KEY` | Ed25519 PKCS#8 私钥,接受 PEM 或 Base64 |
| `TTSTD_WEATHER_DEVELOPER_ID` | 新版 JWT 配置使用的和风开发者 ID,旧 SDK 凭据兼容模式可省略 |
### 生产凭据
生产 k3s 在 `youlai` 命名空间使用独立的 `youlai-weather` Secret。迁移期间沿用旧版 ElderlyDialer 的和风 API Host、项目 ID、JWT 凭据 ID 和 Ed25519 PKCS#8 私钥。旧凭据按 SDK 的 JWT 格式签发,项目 ID 放在 `sub`。切换到新版服务端凭据时,同时配置开发者 ID 作为 `iss`。生产后端通过 Secret 读取私钥。旧凭据曾随旧版 APK 分发,此配置仅用于迁移过渡。
生产 Deployment 的 `app` 容器应添加以下 Secret 引用,保留其他现有的 `envFrom` 项。
```yaml
envFrom:
- secretRef:
name: youlai-weather
```
更新 Secret 后重建 Pod 以重新注入环境变量,并通过已鉴权的天气接口验证实况、逐小时和逐日预报。旧 APK 完成迁移后,轮换生产 Secret 中的凭据,再吊销旧 JWT 凭据。 [和风 JWT 认证](https://dev.qweather.com/docs/configuration/authentication/)
服务端使用和风公开 Weather v1 API 和项目现有 Redis。大陆区县代表点来自 ElderlyDialer 已有的城市表,同一行政区划码沿用表内第一条,坐标保留两位小数用于查询。Redis 的缓存按区县、语言和数据类型共享,使用分布式锁合并并发刷新。上游失败时按键短暂退避,并在有可用旧数据时回退。实况观测超过 2 小时、已结束的小时预报和早于当地当天的逐日预报不返回。
上线时先配置后端凭据,验证三个接口和两类鉴权,再切换 ElderlyDialer 的天气数据源。新版设备迁移完毕后,可以下线 SDK 直连并轮换其旧凭据。
参考 [和风天气 API](https://dev.qweather.com/docs/api/weather/) · [鉴权](https://dev.qweather.com/docs/configuration/authentication/) · [缓存指南](https://dev.qweather.com/docs/best-practices/cache/)
## 分钟预报、预警和空气质量
设备端使用 `/api/v1/sn` 前缀,家属端使用 `/api/v1/client` 前缀,鉴权规则同上。
| 分类 | GET 路径后缀 | 内容 | 缓存时间 |
|---|---|---|---|
| 分钟预报 | `/minutely/5m` | 未来 2 小时,每 5 分钟降水量 | 10 分钟 |
| 预警 | `/weatheralert/current` | 指定位置的官方天气预警 | 最长 20 分钟,已有预警更早到期时提前刷新 |
| 空气质量 | `/airquality/current` | 实时 AQI、污染物和健康建议 | 60 分钟 |
| 空气质量 | `/airquality/hourly` | 未来 24 小时逐小时 AQI | 最长 30 分钟,到 UTC 整点提前刷新 |
| 空气质量 | `/airquality/daily` | 未来 3 天逐日 AQI | 最长 12 小时,到首个预报时段结束时提前刷新 |
这些接口传入 `latitude`、`longitude` 和可选 `lang`。中国大陆传 GCJ-02,其他地区传 WGS84。分钟降水覆盖中国地区。客户端应传实际查询位置,服务端按上游要求保留两位小数,并按网格、分类和语言共享缓存。
响应使用 `Result`。成功时 `data.fetchedAt` 是服务端获取时间,`data.payload` 保留对应和风 API 的原始 JSON 字段、单位、预警生命周期信息和归因声明。预警响应中的 `metadata.zeroResult=true` 表示查询成功且没有预警。界面应按预警有效时间及更新或取消关系展示,分钟预报应略过已过去的时间段。这五条接口过期后重新取数,上游失败时返回项目错误响应。
天气预报的 `periods` 还包含 `details`,逐天包含 `nightDetails` 和 `astronomy`。详情对象提供风向、风速和阵风、降水量和概率、气压、能见度、露点、云量和紫外线指数。降水概率和云量采用 0–100,风速为 m/s,降水量为 mm,气压为 hPa,能见度为 m。天文对象包含日出日落、月升月落和月相,上游没有提供的字段为空。
参考 [分钟预报](https://dev.qweather.com/docs/api/minutely/) · [预警](https://dev.qweather.com/docs/api/warning/) · [空气质量](https://dev.qweather.com/docs/api/air-quality/)
## 缓存时长和定向清理
| 数据 | 和风建议 | 项目上限 |
|---|---:|---:|
| 实时天气 | 10–30 分钟 | 30 分钟 |
| 逐小时天气 | 30–60 分钟 | 60 分钟 |
| 逐天天气 | 1–6 小时 | 6 小时 |
| 分钟降水 | 5–10 分钟 | 10 分钟 |
| 天气预警 | 5–20 分钟 | 20 分钟 |
| 实时空气质量 | 30–60 分钟 | 60 分钟 |
| 逐小时空气质量 | 指南未单列 | 30 分钟 |
| 逐天空气质量 | 8–12 小时 | 12 小时 |
当整点、跨日或预警到期的边界早于上限时,以对应边界为准。逐天空气质量采用上游的 `forecastEndTime`,以查询点预报时段为准。天气预报在上游故障时可能返回仍可展示的旧缓存,并通过 `stale` 标识。项目的区划映射来自已有城市表,不缓存 GeoAPI 查询结果。 [和风缓存指南](https://dev.qweather.com/docs/best-practices/cache/)
运维可在应用使用的 Redis 数据库中按完整键清除指定位置、语言和类型,同时清除该键的 `:cooldown`。下次请求会触发刷新,无需重新发布。若清理时已有上游请求正在刷新,该请求完成后会写入本次取得的新数据。
- 区县预报键为 `ttstd:weather:v2:<adCode>:<lang>:<current|hourly|daily>`。
- 网格天气键为 `ttstd:weather:point:v2:<MINUTELY|ALERTS|AIR_CURRENT|AIR_HOURLY|AIR_DAILY>:<latitude>:<longitude>:<lang>`。坐标使用两位小数。
例如使用已连接到应用 Redis 数据库的命令行清除海淀区中文实况,或清除代表点的中文预警。
```redis
UNLINK ttstd:weather:v2:110108:zh:current ttstd:weather:v2:110108:zh:current:cooldown
UNLINK ttstd:weather:point:v2:ALERTS:39.96:116.31:zh ttstd:weather:point:v2:ALERTS:39.96:116.31:zh:cooldown
```
@@ -0,0 +1,52 @@
package com.youlai.boot.device.weather;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/api/v1/sn", "/api/v1/client"})
public class NearbyWeatherController {
private final NearbyWeatherService service;
@Operation(summary = "查询分钟级降水预报", tags = "分钟预报")
@GetMapping("/minutely/5m")
public Result<NearbyWeatherService.Response> minutely(@RequestParam String latitude, @RequestParam String longitude,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.get(NearbyWeatherService.Product.MINUTELY, latitude, longitude, lang));
}
@Operation(summary = "查询实时天气预警", tags = "预警")
@GetMapping("/weatheralert/current")
public Result<NearbyWeatherService.Response> alerts(@RequestParam String latitude, @RequestParam String longitude,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.get(NearbyWeatherService.Product.ALERTS, latitude, longitude, lang));
}
@Operation(summary = "查询实时空气质量", tags = "空气质量")
@GetMapping("/airquality/current")
public Result<NearbyWeatherService.Response> airCurrent(@RequestParam String latitude, @RequestParam String longitude,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.get(NearbyWeatherService.Product.AIR_CURRENT, latitude, longitude, lang));
}
@Operation(summary = "查询逐小时空气质量", tags = "空气质量")
@GetMapping("/airquality/hourly")
public Result<NearbyWeatherService.Response> airHourly(@RequestParam String latitude, @RequestParam String longitude,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.get(NearbyWeatherService.Product.AIR_HOURLY, latitude, longitude, lang));
}
@Operation(summary = "查询逐天空气质量", tags = "空气质量")
@GetMapping("/airquality/daily")
public Result<NearbyWeatherService.Response> airDaily(@RequestParam String latitude, @RequestParam String longitude,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.get(NearbyWeatherService.Product.AIR_DAILY, latitude, longitude, lang));
}
}
@@ -0,0 +1,175 @@
package com.youlai.boot.device.weather;
import com.youlai.boot.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class NearbyWeatherService {
private static final Set<String> LANGUAGES = Set.of("zh", "zh-hant", "en");
private final QWeatherClient upstream;
private final StringRedisTemplate redis;
private final ObjectProvider<RedissonClient> redisson;
private final ObjectMapper json;
Response get(Product product, String latitude, String longitude, String lang) {
String lat = gridCoordinate(latitude, 90);
String lng = gridCoordinate(longitude, 180);
if (!LANGUAGES.contains(lang)) {
throw new BusinessException("不支持的天气语言");
}
String key = "ttstd:weather:point:v2:" + product.name() + ":" + lat + ":" + lng + ":" + lang;
String cached = redis.opsForValue().get(key);
if (cached != null) {
return json.readValue(cached, Response.class);
}
try {
var lock = redisson.getObject().getLock(key + ":refresh");
if (!lock.tryLock(1, TimeUnit.SECONDS)) {
cached = redis.opsForValue().get(key);
if (cached == null) {
throw unavailable();
}
return json.readValue(cached, Response.class);
}
try {
cached = redis.opsForValue().get(key);
if (cached != null) {
return json.readValue(cached, Response.class);
}
return refresh(product, lat, lng, lang, key);
} finally {
lock.unlock();
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw unavailable();
}
}
private Response refresh(Product product, String lat, String lng, String lang, String key)
throws InterruptedException {
String cooldown = key + ":cooldown";
if (Boolean.TRUE.equals(redis.hasKey(cooldown))) {
throw unavailable();
}
String path = product == Product.MINUTELY
? product.path + "?location=" + lng + "%2C" + lat + "&lang=" + lang
: product.path + "/" + lat + "/" + lng + "?lang=" + lang;
JsonNode payload;
try {
payload = upstream.fetch(path);
if (!payload.isObject() || (product == Product.MINUTELY
? !"200".equals(payload.path("code").asString()) || !payload.path("minutely").isArray()
: !payload.path("metadata").isObject())) {
throw new IOException("Unexpected response");
}
} catch (IOException | GeneralSecurityException | RuntimeException ex) {
log.warn("Weather refresh failed for {} ({})", product, ex.getClass().getSimpleName());
redis.opsForValue().set(cooldown, "1", Duration.ofSeconds(30));
throw unavailable();
}
Instant now = Instant.now();
Response response = new Response(now.toString(), payload);
Duration ttl = cacheLifetime(product, payload, now);
if (!ttl.isZero() && !ttl.isNegative()) {
redis.opsForValue().set(key, json.writeValueAsString(response), ttl);
}
return response;
}
private static Duration cacheLifetime(Product product, JsonNode payload, Instant now) {
Instant expires = now.plus(product.ttl);
switch (product) {
case AIR_HOURLY -> expires = now.truncatedTo(ChronoUnit.HOURS).plus(1, ChronoUnit.HOURS);
case AIR_DAILY -> {
Instant firstEnd = readTime(payload.path("days").path(0).path("forecastEndTime"));
if (firstEnd == null) {
return Duration.ZERO;
}
if (firstEnd.isBefore(expires)) {
expires = firstEnd;
}
}
case ALERTS -> {
for (JsonNode alert : payload.path("alerts")) {
Instant alertEnd = readTime(alert.path("expireTime"));
if (alertEnd != null && alertEnd.isBefore(expires)) {
expires = alertEnd;
}
}
}
default -> { }
}
Duration remaining = Duration.between(now, expires);
return remaining.compareTo(product.ttl) < 0 ? remaining : product.ttl;
}
private static Instant readTime(JsonNode node) {
if (!node.isString()) {
return null;
}
try {
return OffsetDateTime.parse(node.asString()).toInstant();
} catch (DateTimeParseException ex) {
return null;
}
}
private static String gridCoordinate(String input, int limit) {
if (input == null || !input.matches("[+-]?\\d{1,3}(?:\\.\\d{1,10})?")) {
throw new BusinessException("天气查询坐标无效");
}
BigDecimal value = new BigDecimal(input);
if (value.abs().compareTo(BigDecimal.valueOf(limit)) > 0) {
throw new BusinessException("天气查询坐标超出范围");
}
return value.setScale(2, RoundingMode.HALF_UP).toPlainString();
}
private static BusinessException unavailable() {
return new BusinessException("天气数据暂不可用,请稍后重试");
}
enum Product {
MINUTELY("v7/minutely/5m", 10),
ALERTS("weatheralert/v1/current", 20),
AIR_CURRENT("airquality/v1/current", 60),
AIR_HOURLY("airquality/v1/hourly", 30),
AIR_DAILY("airquality/v1/daily", 720);
private final String path;
private final Duration ttl;
Product(String path, long minutes) {
this.path = path;
this.ttl = Duration.ofMinutes(minutes);
}
}
public record Response(String fetchedAt, JsonNode payload) {}
}
@@ -0,0 +1,96 @@
package com.youlai.boot.device.weather;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
@Component
class QWeatherClient {
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
private final ObjectMapper json;
private final Environment config;
private String token;
private long renewAt;
QWeatherClient(ObjectMapper json, Environment config) {
this.json = json;
this.config = config;
}
JsonNode fetch(String path) throws IOException, InterruptedException, GeneralSecurityException {
String host = config.getRequiredProperty("ttstd.weather.host");
if (!host.matches("[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?")) {
throw new IllegalStateException("Invalid weather API host");
}
HttpRequest request = HttpRequest.newBuilder(URI.create("https://" + host + "/" + path))
.timeout(Duration.ofSeconds(4))
.header("Authorization", "Bearer " + token())
.header("Accept-Encoding", "gzip")
.GET().build();
HttpResponse<byte[]> response = http.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() != 200) {
throw new IOException("Weather upstream HTTP " + response.statusCode());
}
byte[] body = response.body();
if (response.headers().firstValue("Content-Encoding").filter("gzip"::equalsIgnoreCase).isPresent()) {
try (var stream = new GZIPInputStream(new ByteArrayInputStream(body))) {
body = stream.readAllBytes();
}
}
return json.readTree(body);
}
private synchronized String token() throws GeneralSecurityException {
long now = Instant.now().getEpochSecond();
if (token != null && now < renewAt) {
return token;
}
String pem = config.getRequiredProperty("ttstd.weather.private-key")
.replace("\\n", "\n").replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "").replaceAll("\\s", "");
var key = KeyFactory.getInstance("Ed25519")
.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem)));
String header = encode(json.writeValueAsBytes(Map.of(
"alg", "EdDSA", "kid", config.getRequiredProperty("ttstd.weather.key-id"))));
Map<String, Object> claims = new HashMap<>();
claims.put("sub", config.getRequiredProperty("ttstd.weather.project-id"));
claims.put("iat", now - 30);
claims.put("exp", now + 900);
String developerId = config.getProperty("ttstd.weather.developer-id");
if (developerId != null && !developerId.isBlank()) {
claims.put("iss", developerId);
}
String payload = encode(json.writeValueAsBytes(claims));
String input = header + "." + payload;
Signature signer = Signature.getInstance("Ed25519");
signer.initSign(key);
signer.update(input.getBytes(StandardCharsets.US_ASCII));
token = input + "." + encode(signer.sign());
renewAt = now + 840;
return token;
}
private static String encode(byte[] bytes) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}
@@ -0,0 +1,40 @@
package com.youlai.boot.device.weather;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "天气预报")
@RestController
@RequiredArgsConstructor
@RequestMapping({"/api/v1/sn/weather", "/api/v1/client/weather"})
public class WeatherController {
private final WeatherService service;
@Operation(summary = "查询区县实时天气")
@GetMapping("/current")
public Result<WeatherResponse> current(@RequestParam String adCode,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.getWeather("current", adCode, lang));
}
@Operation(summary = "查询区县逐小时天气")
@GetMapping("/hourly")
public Result<WeatherResponse> hourly(@RequestParam String adCode,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.getWeather("hourly", adCode, lang));
}
@Operation(summary = "查询区县逐天天气")
@GetMapping("/daily")
public Result<WeatherResponse> daily(@RequestParam String adCode,
@RequestParam(defaultValue = "zh") String lang) {
return Result.success(service.getWeather("daily", adCode, lang));
}
}
@@ -0,0 +1,22 @@
package com.youlai.boot.device.weather;
import java.util.List;
/** The same JSON contract is used by device and family clients. */
public record WeatherResponse(String adCode, String areaName, String timeZone, String fetchedAt,
boolean stale, List<String> attributions, List<Period> periods) {
public record Condition(String code, String text) {}
public record Period(String time, String endTime, String localDate, Condition condition,
Condition nightCondition, Double temperatureC, Double feelsLikeC,
Double minTemperatureC, Double maxTemperatureC, Double humidityPercent,
Details details, Details nightDetails, Astronomy astronomy) {}
public record Details(Double windDirectionDegrees, String windCompass, Double windSpeedMps,
Double windGustMps, Double precipitationMm, Double precipitationProbabilityPercent,
String precipitationType, Double pressureHpa, Double visibilityMeters,
Double dewPointC, Double cloudCoverPercent, Double uvIndex) {}
public record Astronomy(String sunrise, String sunset, String moonrise, String moonset, String moonPhase) {}
}
@@ -0,0 +1,257 @@
package com.youlai.boot.device.weather;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.device.weather.WeatherResponse.Condition;
import com.youlai.boot.device.weather.WeatherResponse.Astronomy;
import com.youlai.boot.device.weather.WeatherResponse.Details;
import com.youlai.boot.device.weather.WeatherResponse.Period;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class WeatherService {
private static final Duration RETENTION = Duration.ofHours(6);
private static final ZoneId CHINA_ZONE = ZoneId.of("Asia/Shanghai");
private static final Set<String> LANGUAGES = Set.of("zh", "zh-hant", "en");
private static final Map<String, Product> PRODUCTS = Map.of(
"current", new Product(Duration.ofMinutes(30), ""),
"hourly", new Product(Duration.ofHours(1), "&hours=24"),
"daily", new Product(Duration.ofHours(6), "&days=10"));
private final QWeatherClient upstream;
private final StringRedisTemplate redis;
private final ObjectProvider<RedissonClient> redisson;
private final ObjectMapper json;
private final Map<String, Area> areas;
WeatherService(QWeatherClient upstream, StringRedisTemplate redis,
ObjectProvider<RedissonClient> redisson, ObjectMapper json) throws IOException {
this.upstream = upstream;
this.redis = redis;
this.redisson = redisson;
this.json = json;
Map<String, Area> catalog = new HashMap<>();
try (var reader = new BufferedReader(new InputStreamReader(
new ClassPathResource("weather/mainland-areas.tsv").getInputStream(), StandardCharsets.UTF_8))) {
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\t");
catalog.put(fields[0], new Area(fields[1], fields[2], fields[3]));
}
}
this.areas = Map.copyOf(catalog);
}
public WeatherResponse getWeather(String type, String adCode, String lang) {
Product product = PRODUCTS.get(type);
Area area = areas.get(adCode);
if (product == null || area == null || !LANGUAGES.contains(lang)) {
throw new BusinessException("不支持的天气类型、地区或语言");
}
String key = "ttstd:weather:v2:" + adCode + ":" + lang + ":" + type;
WeatherResponse cached = read(key);
if (fresh(cached, type, product)) {
return visible(cached, type, false);
}
try {
var lock = redisson.getObject().getLock(key + ":refresh");
if (!lock.tryLock(cached == null ? 1 : 0, TimeUnit.SECONDS)) {
return fallback(read(key), type, product);
}
try {
cached = read(key);
if (fresh(cached, type, product)) {
return visible(cached, type, false);
}
String cooldown = key + ":cooldown";
if (Boolean.TRUE.equals(redis.hasKey(cooldown))) {
return fallback(cached, type, product);
}
try {
String path = "weather/v1/" + type + "/" + area.latitude() + "/" + area.longitude()
+ "?lang=" + lang + product.query();
WeatherResponse updated = map(upstream.fetch(path), type, adCode, area);
WeatherResponse result = visible(updated, type, false);
redis.opsForValue().set(key, json.writeValueAsString(updated), RETENTION);
return result;
} catch (IOException | GeneralSecurityException | RuntimeException ex) {
log.warn("Weather refresh failed for {} ({})", key, ex.getClass().getSimpleName());
redis.opsForValue().set(cooldown, "1", Duration.ofSeconds(30));
return fallback(cached, type, product);
}
} finally {
lock.unlock();
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return fallback(cached, type, product);
}
}
private WeatherResponse read(String key) {
String value = redis.opsForValue().get(key);
return value == null ? null : json.readValue(value, WeatherResponse.class);
}
private static boolean fresh(WeatherResponse response, String type, Product product) {
if (response == null) {
return false;
}
Instant fetched = Instant.parse(response.fetchedAt());
Instant now = Instant.now();
if (!now.isBefore(fetched.plus(product.freshFor()))) {
return false;
}
return switch (type) {
case "hourly" -> fetched.truncatedTo(ChronoUnit.HOURS).equals(now.truncatedTo(ChronoUnit.HOURS));
case "daily" -> fetched.atZone(CHINA_ZONE).toLocalDate().equals(now.atZone(CHINA_ZONE).toLocalDate());
default -> true;
};
}
private static WeatherResponse fallback(WeatherResponse response, String type, Product product) {
if (response == null) {
throw new BusinessException("天气暂不可用,请稍后重试");
}
return visible(response, type, !fresh(response, type, product));
}
private static WeatherResponse visible(WeatherResponse response, String type, boolean stale) {
Instant now = Instant.now();
List<Period> periods = response.periods().stream().filter(period -> switch (type) {
case "daily" -> period.localDate().compareTo(now.atZone(CHINA_ZONE).toLocalDate().toString()) >= 0;
case "hourly" -> Instant.parse(period.endTime()).isAfter(now);
default -> Instant.parse(period.time()).plus(Duration.ofHours(2)).isAfter(now);
}).toList();
if (periods.isEmpty()) {
throw new BusinessException("天气暂不可用,请稍后重试");
}
return new WeatherResponse(response.adCode(), response.areaName(), response.timeZone(), response.fetchedAt(),
stale, response.attributions(), periods);
}
private static WeatherResponse map(JsonNode root, String type, String adCode, Area area) {
List<String> attributions = new ArrayList<>();
for (JsonNode item : root.path("metadata").path("attributions")) {
if (item.isString()) {
attributions.add(item.asString());
}
}
List<Period> periods = new ArrayList<>();
switch (type) {
case "current" -> periods.add(temperaturePeriod(root, "validTime", false));
case "hourly" -> root.path("hours").forEach(item -> periods.add(temperaturePeriod(item, "forecastTime", true)));
case "daily" -> root.path("days").forEach(day -> {
Instant time = OffsetDateTime.parse(day.path("forecastStartTime").asString()).toInstant();
Instant end = OffsetDateTime.parse(day.path("forecastEndTime").asString()).toInstant();
Instant daytime = OffsetDateTime.parse(day.path("daytime").path("forecastStartTime").asString()).toInstant();
periods.add(new Period(time.toString(), end.toString(), localDate(daytime),
condition(day.path("daytime")), condition(day.path("nighttime")), null, null,
number(day.path("temperatureMin").path("value")), number(day.path("temperatureMax").path("value")),
humidity(day.path("daytime")), details(day.path("daytime"), day.path("uvIndexMax")),
details(day.path("nighttime"), day.path("nighttime").path("uvIndex")),
astronomy(day.path("astro"))));
});
default -> throw new IllegalArgumentException("Unknown weather type");
}
if (periods.isEmpty() || attributions.isEmpty()) {
throw new IllegalStateException("Weather response missing forecast or attribution");
}
return new WeatherResponse(adCode, area.name(), CHINA_ZONE.getId(), Instant.now().toString(), false,
attributions, periods);
}
private static Period temperaturePeriod(JsonNode node, String timeField, boolean hourly) {
Instant time = OffsetDateTime.parse(node.path(timeField).asString()).toInstant();
return new Period(time.toString(), hourly ? time.plus(Duration.ofHours(1)).toString() : null,
localDate(time), condition(node), null, number(node.path("temperature").path("value")),
number(node.path("feelsLike").path("value")), null, null, humidity(node),
details(node, node.path("uvIndex")), null, null);
}
private static Details details(JsonNode node, JsonNode uv) {
JsonNode wind = node.path("wind");
JsonNode direction = wind.path("direction");
JsonNode precipitation = node.path("precipitation");
JsonNode gust = node.has("windGust") ? node.path("windGust") : node.path("windGustMax");
return new Details(number(direction.path("degree")), text(direction.path("compass")),
number(wind.path("speed").path("value")), number(gust.path("value")),
number(precipitation.path("amount").path("value")), percent(precipitation.path("probability")),
text(precipitation.path("type")), number(node.path("pressure").path("value")),
number(node.path("visibility").path("value")), number(node.path("dewPoint").path("value")),
percent(node.path("cloudCover")), number(uv));
}
private static Astronomy astronomy(JsonNode node) {
return new Astronomy(optionalTime(node.path("sunrise")), optionalTime(node.path("sunset")),
optionalTime(node.path("moonrise")), optionalTime(node.path("moonset")), text(node.path("moonPhase")));
}
private static String optionalTime(JsonNode node) {
String value = text(node);
if (value == null || value.isBlank()) {
return null;
}
try {
return OffsetDateTime.parse(value).toInstant().toString();
} catch (java.time.format.DateTimeParseException ex) {
return null;
}
}
private static String text(JsonNode node) {
return node.isString() ? node.asString() : null;
}
private static String localDate(Instant instant) {
return instant.atZone(CHINA_ZONE).toLocalDate().toString();
}
private static Condition condition(JsonNode node) {
JsonNode condition = node.path("condition");
return new Condition(condition.path("code").asString(), condition.path("text").asString());
}
private static Double number(JsonNode node) {
return node.isNumber() ? node.asDouble() : null;
}
private static Double humidity(JsonNode node) {
return percent(node.path("humidity"));
}
private static Double percent(JsonNode node) {
Double value = number(node);
return value == null ? null : value * 100;
}
private record Area(String name, String latitude, String longitude) {}
private record Product(Duration freshFor, String query) {}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,45 @@
package com.youlai.boot.device.weather;
import org.junit.jupiter.api.Test;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import static org.junit.jupiter.api.Assertions.assertEquals;
class WeatherTimestampTest {
@Test
void mapsMinutePrecisionForAllWeatherProducts() throws Exception {
WeatherResponse.Period current = period("current", """
{"validTime":"2026-11-29T13:45Z","condition":{"code":"101","text":"多云"}}
""");
assertEquals("2026-11-29T13:45:00Z", current.time());
WeatherResponse.Period hourly = period("hourly", """
{"hours":[{"forecastTime":"2026-11-29T22:00+08:00","condition":{"code":"101","text":"多云"}}]}
""");
assertEquals("2026-11-29T14:00:00Z", hourly.time());
assertEquals("2026-11-29T15:00:00Z", hourly.endTime());
WeatherResponse.Period daily = period("daily", """
{"days":[{"forecastStartTime":"2026-11-29T22:00Z","forecastEndTime":"2026-11-30T22:00Z",
"daytime":{"forecastStartTime":"2026-11-30T07:00+08:00","condition":{"code":"100","text":"晴"}},
"nighttime":{"condition":{"code":"150","text":"晴"}},"astro":{"sunrise":"2026-11-30T06:44+08:00"}}]}
""");
assertEquals("2026-11-30", daily.localDate());
assertEquals("2026-11-29T22:44:00Z", daily.astronomy().sunrise());
}
private static WeatherResponse.Period period(String type, String json) throws Exception {
JsonNode node = JsonMapper.builder().build().readTree(
"{\"metadata\":{\"attributions\":[\"QWeather\"]}," + json.strip().substring(1));
Class<?> areaType = Class.forName(WeatherService.class.getName() + "$Area");
var constructor = areaType.getDeclaredConstructor(String.class, String.class, String.class);
constructor.setAccessible(true);
var mapper = WeatherService.class.getDeclaredMethod("map", JsonNode.class, String.class, String.class, areaType);
mapper.setAccessible(true);
var result = (WeatherResponse) mapper.invoke(null, node, type, "440307",
constructor.newInstance("龙岗", "22.72", "114.25"));
return result.periods().get(0);
}
}