Java项目建立天气预报功能

在 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. 安全与优化建议

  1. 敏感配置(API 密钥)应使用环境变量或配置中心管理
  2. 对 API 调用添加超时设置:
@Bean
public RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setConnectTimeout(5000);
    requestFactory.setReadTimeout(5000);
    return new RestTemplate(requestFactory);
}
  1. 实现 API 调用频率控制,避免超出第三方服务限制
  2. 考虑添加降级策略,当第三方 API 不可用时返回缓存数据或默认信息

通过以上实现,后端服务可以稳定地获取并提供天气预报功能,同时具备良好的可扩展性和容错能力。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值