在 Java 项目中实现天气预报功能的后端接入,主要涉及第三方 API 调用、数据解析和接口封装三个核心环节。以下是具体实现方案:
1. 选择第三方天气 API
推荐使用主流天气服务提供商,如:
- 高德开放平台天气 API
- 百度地图开放平台天气服务
- 和风天气 API
这些服务通常提供免费额度,需先注册获取 API 密钥(key)。
2. 核心实现步骤
2.1 添加 HTTP 客户端依赖
使用 Spring Boot 的RestTemplate或 OkHttp 作为 HTTP 客户端,在pom.xml中添加依赖:
<!-- Spring Boot RestTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 可选:OkHttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
2.2 配置 API 参数
在application.properties中配置 API 相关参数:
# 高德天气API配置
weather.api.key=your_api_key
weather.api.url=https://restapi.amap.com/v3/weather/weatherInfo
weather.api.city=110000 # 城市编码,北京
2.3 创建数据模型
定义接收天气数据的实体类(以高德 API 为例):
@Data
public class WeatherResponse {
private String status; // 返回状态
private String count; // 结果数量
private List<WeatherData> lives; // 实时天气数据
@Data
public static class WeatherData {
private String city; // 城市名称
private String temperature; // 温度
private String weather; // 天气状况
private String winddirection; // 风向
private String windpower; // 风力
private String humidity; // 湿度
private String reporttime; // 数据发布时间
}
}
2.4 实现 API 调用服务
创建天气服务类,负责调用第三方 API 并解析返回结果:
@Service
public class WeatherService {
@Value("${weather.api.key}")
private String apiKey;
@Value("${weather.api.url}")
private String apiUrl;
@Autowired
private RestTemplate restTemplate;
/**
* 获取指定城市的实时天气
*/
public WeatherResponse.WeatherData getRealTimeWeather(String cityCode) {
// 构建请求参数
Map<String, String> params = new HashMap<>();
params.put("key", apiKey);
params.put("city", cityCode);
params.put("extensions", "base"); // 基础天气信息
// 发起GET请求
ResponseEntity<WeatherResponse> response = restTemplate.getForEntity(
apiUrl + "?key={key}&city={city}&extensions={extensions}",
WeatherResponse.class,
params
);
// 处理响应结果
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
WeatherResponse weatherResponse = response.getBody();
if ("1".equals(weatherResponse.getStatus()) && !CollectionUtils.isEmpty(weatherResponse.getLives())) {
return weatherResponse.getLives().get(0);
}
}
throw new RuntimeException("获取天气信息失败");
}
}
2.5 封装接口供前端调用
创建 Controller 层暴露接口:
@RestController
@RequestMapping("/api/weather")
public class WeatherController {
@Autowired
private WeatherService weatherService;
@GetMapping("/realtime")
public ResponseEntity<WeatherResponse.WeatherData> getRealTimeWeather(
@RequestParam(defaultValue = "110000") String cityCode) {
return ResponseEntity.ok(weatherService.getRealTimeWeather(cityCode));
}
}
3. 增强功能实现
3.1 缓存机制
添加缓存减少 API 调用次数,使用 Spring Cache:
@EnableCaching
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("weather");
}
}
在服务方法上添加缓存注解:
@Cacheable(value = "weather", key = "#cityCode", expireAfterWrite = 30, timeUnit = TimeUnit.MINUTES)
public WeatherResponse.WeatherData getRealTimeWeather(String cityCode) {
// 原有实现
}
3.2 异常处理
创建全局异常处理器:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
4. 安全与优化建议
- 敏感配置(API 密钥)应使用环境变量或配置中心管理
- 对 API 调用添加超时设置:
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(5000);
requestFactory.setReadTimeout(5000);
return new RestTemplate(requestFactory);
}
- 实现 API 调用频率控制,避免超出第三方服务限制
- 考虑添加降级策略,当第三方 API 不可用时返回缓存数据或默认信息
通过以上实现,后端服务可以稳定地获取并提供天气预报功能,同时具备良好的可扩展性和容错能力。
2028

被折叠的 条评论
为什么被折叠?



