SpringBoot整合高德地圖實(shí)現(xiàn)天氣預(yù)報(bào)功能
一、前言
在當(dāng)今數(shù)字化時(shí)代,天氣預(yù)報(bào)功能在眾多應(yīng)用中扮演著重要角色。通過(guò)整合高德地圖提供的天氣API,我們可以輕松地在自己的SpringBoot項(xiàng)目中實(shí)現(xiàn)這一功能,為用戶(hù)提供實(shí)時(shí)和未來(lái)幾天的天氣信息。本文將詳細(xì)介紹如何在SpringBoot項(xiàng)目中整合高德地圖的天氣預(yù)報(bào)功能,包括環(huán)境搭建、代碼實(shí)現(xiàn)、定時(shí)任務(wù)設(shè)置等關(guān)鍵步驟,確保大家能夠按照教程成功實(shí)現(xiàn)功能。
二、環(huán)境搭建
(一)創(chuàng)建SpringBoot項(xiàng)目
使用Spring Initializr
- 訪問(wèn) Spring Initializr 網(wǎng)站。
- 選擇項(xiàng)目元數(shù)據(jù),如項(xiàng)目名稱(chēng)、包名等。
- 添加依賴(lài):
Spring Web、Spring Boot DevTools(可選,方便開(kāi)發(fā)時(shí)熱部署)。 - 點(diǎn)擊“Generate”按鈕下載項(xiàng)目壓縮包,解壓后導(dǎo)入到你的IDE(如IntelliJ IDEA或Eclipse)中。
項(xiàng)目結(jié)構(gòu)示例
spring-boot-weather ├── src │ ├── main │ │ ├── java │ │ │ └── com.example.weather │ │ │ ├── controller │ │ │ ├── service │ │ │ ├── entity │ │ │ ├── config │ │ │ └── WeatherApplication.java │ │ └── resources │ │ ├── application.yml │ │ └── static │ └── test │ └── java │ └── com.example.weather │ └── WeatherApplicationTests.java └── pom.xml
(二)添加依賴(lài)
在pom.xml文件中添加必要的依賴(lài),確保項(xiàng)目能夠使用Spring Web和定時(shí)任務(wù)等功能。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
(三)高德地圖API申請(qǐng)
注冊(cè)高德開(kāi)放平臺(tái)賬號(hào)
- 訪問(wèn) 高德開(kāi)放平臺(tái) 官網(wǎng),注冊(cè)賬號(hào)并登錄。
- 在“控制臺(tái)”中創(chuàng)建應(yīng)用,獲取
API Key。該Key將用于后續(xù)調(diào)用高德地圖的天氣API。
配置
application.yml- 將獲取到的
API Key和天氣API的URL配置到application.yml文件中。
- 將獲取到的
amap-weather-config: weatherurl: https://restapi.amap.com/v3/weather/weatherInfo key: YOUR_API_KEY
三、代碼實(shí)現(xiàn)
(一)配置類(lèi)
創(chuàng)建一個(gè)配置類(lèi)AmapWeatherConfig,用于讀取application.yml中的高德地圖天氣API配置。
package com.example.weather.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "amap-weather-config")
@Getter
@Setter
public class AmapWeatherConfig {
private String weatherurl;
private String key;
}
(二)實(shí)體類(lèi)
定義兩個(gè)實(shí)體類(lèi)Live和WeatherForecast,分別用于存儲(chǔ)實(shí)時(shí)天氣和預(yù)報(bào)天氣的數(shù)據(jù)。
實(shí)時(shí)天氣實(shí)體類(lèi)Live
package com.example.weather.entity;
import lombok.Data;
@Data
public class Live {
private String province;
private String city;
private String adcode;
private String weather;
private String temperature;
private String winddirection;
private String windpower;
private String humidity;
private String reporttime;
}
預(yù)報(bào)天氣實(shí)體類(lèi)WeatherForecast
package com.example.weather.entity;
import lombok.Data;
@Data
public class WeatherForecast {
private String province;
private String city;
private String adcode;
private String date;
private String week;
private String dayWeather;
private String dayWeatherImg;
private String nightWeather;
private String nightWeatherImg;
private String dayTemp;
private String nightTemp;
private String dayWind;
private String nightWind;
private String dayPower;
private String nightPower;
private String reportTime;
}
(三)服務(wù)層
創(chuàng)建WeatherService類(lèi),用于調(diào)用高德地圖的天氣API,并將返回的數(shù)據(jù)封裝到實(shí)體類(lèi)中。
package com.example.weather.service;
import com.example.weather.config.AmapWeatherConfig;
import com.example.weather.entity.Live;
import com.example.weather.entity.WeatherForecast;
import com.example.weather.common.WeatherConstant;
import com.example.weather.enums.WeatherType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
@Slf4j
public class WeatherService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private AmapWeatherConfig amapWeatherConfig;
/**
* 獲取實(shí)時(shí)天氣
*
* @param adcode 城市編碼
* @return 實(shí)時(shí)天氣實(shí)體類(lèi)
*/
public Live getLiveWeather(String adcode) {
String sendUrl = amapWeatherConfig.getWeatherurl() +
"?key=" + amapWeatherConfig.getKey() +
"&city=" + adcode +
"&extensions=base";
ResponseEntity<GaoDeResult> responseEntity = restTemplate.getForEntity(sendUrl, GaoDeResult.class);
// 請(qǐng)求異常,可能由于網(wǎng)絡(luò)等原因
HttpStatus statusCode = responseEntity.getStatusCode();
if (!HttpStatus.OK.equals(statusCode)) {
log.info("Request for Gaode interface error");
return null;
}
// 請(qǐng)求失敗
GaoDeResult gaoDeResult = responseEntity.getBody();
String status = gaoDeResult.getStatus();
if (!status.equals(WeatherConstant.SUCCESS)) {
log.info("Request for Gaode interface failed");
return null;
}
List<Live> lives = gaoDeResult.getLives();
if (CollectionUtils.isEmpty(lives)) {
return null;
}
// 實(shí)況天氣
return lives.get(0);
}
/**
* 獲取未來(lái)幾天的天氣預(yù)報(bào)
*
* @param adcode 城市編碼
* @return 天氣預(yù)報(bào)列表
*/
public List<WeatherForecast> getForecastWeather(String adcode) {
String sendUrl = amapWeatherConfig.getWeatherurl() +
"?key=" + amapWeatherConfig.getKey() +
"&city=" + adcode +
"&extensions=all";
ResponseEntity<GaoDeResult> responseEntity = restTemplate.getForEntity(sendUrl, GaoDeResult.class);
// 請(qǐng)求異常,可能由于網(wǎng)絡(luò)等原因
HttpStatus statusCode = responseEntity.getStatusCode();
if (!HttpStatus.OK.equals(statusCode)) {
log.info("Request for Gaode interface error");
return Collections.emptyList();
}
// 請(qǐng)求失敗
GaoDeResult gaoDeResult = responseEntity.getBody();
String status = gaoDeResult.getStatus();
if (!status.equals(WeatherConstant.SUCCESS)) {
log.info("Request for Gaode interface failed");
return Collections.emptyList();
}
List<Forecast> forecasts = gaoDeResult.getForecasts();
if (CollectionUtils.isEmpty(forecasts)) {
return Collections.emptyList();
}
// 預(yù)報(bào)天氣
Forecast forecast = forecasts.get(0);
List<WeatherForecast> weatherForecastList = new ArrayList<>();
List<Forecast.Cast> casts = forecast.getCasts();
for (Forecast.Cast cast : casts) {
WeatherForecast weatherForecast = new WeatherForecast();
weatherForecast.setProvince(forecast.getProvince());
weatherForecast.setCity(forecast.getCity());
weatherForecast.setAdcode(forecast.getAdcode());
weatherForecast.setDate(cast.getDate());
weatherForecast.setWeek(cast.getWeek());
weatherForecast.setDayWeather(cast.getDayweather());
weatherForecast.setDayWeatherImg(WeatherType.getCodeByDes(cast.getDayweather()));
weatherForecast.setNightWeather(cast.getNightweather());
weatherForecast.setNightWeatherImg(WeatherType.getCodeByDes(cast.getNightweather()));
weatherForecast.setDayTemp(cast.getDaytemp());
weatherForecast.setNightTemp(cast.getNighttemp());
weatherForecast.setDayWind(cast.getDaywind());
weatherForecast.setNightWind(cast.getNightwind());
weatherForecast.setDayPower(cast.getDaypower());
weatherForecast.setNightPower(cast.getNightpower());
weatherForecast.setReportTime(forecast.getReporttime());
weatherForecastList.add(weatherForecast);
}
return weatherForecastList;
}
}
(四)實(shí)體類(lèi)GaoDeResult和Forecast
高德地圖API返回的數(shù)據(jù)結(jié)構(gòu)較為復(fù)雜,需要定義GaoDeResult和Forecast類(lèi)來(lái)接收和處理這些數(shù)據(jù)。
GaoDeResult類(lèi)
package com.example.weather.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class GaoDeResult {
private String status;
private String info;
private String infocode;
@JsonProperty("lives")
private List<Live> lives;
@JsonProperty("forecasts")
private List<Forecast> forecasts;
}
Forecast類(lèi)
package com.example.weather.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class Forecast {
private String province;
private String city;
private String adcode;
private String reporttime;
@JsonProperty("casts")
private List<Cast> casts;
@Data
public static class Cast {
private String date;
private String week;
private String dayweather;
private String nightweather;
private String daytemp;
private String nighttemp;
private String daywind;
private String nightwind;
private String daypower;
private String nightpower;
}
}
(五)控制器層
創(chuàng)建WeatherController類(lèi),用于處理前端請(qǐng)求,并調(diào)用服務(wù)層的方法獲取天氣數(shù)據(jù)。
package com.example.weather.controller;
import com.example.weather.entity.Live;
import com.example.weather.entity.WeatherForecast;
import com.example.weather.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/weather")
public class WeatherController {
@Autowired
private WeatherService weatherService;
/**
* 獲取實(shí)時(shí)天氣
*
* @param adcode 城市編碼
* @return 實(shí)時(shí)天氣數(shù)據(jù)
*/
@GetMapping("/live")
public Live getLiveWeather(@RequestParam String adcode) {
return weatherService.getLiveWeather(adcode);
}
/**
* 獲取未來(lái)幾天的天氣預(yù)報(bào)
*
* @param adcode 城市編碼
* @return 天氣預(yù)報(bào)數(shù)據(jù)
*/
@GetMapping("/forecast")
public List<WeatherForecast> getForecastWeather(@RequestParam String adcode) {
return weatherService.getForecastWeather(adcode);
}
}
(六)定時(shí)任務(wù)
為了定期更新天氣數(shù)據(jù),可以使用Spring的定時(shí)任務(wù)功能。創(chuàng)建WeatherTask類(lèi),設(shè)置定時(shí)任務(wù)。
package com.example.weather.task;
import com.example.weather.entity.Live;
import com.example.weather.entity.WeatherForecast;
import com.example.weather.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class WeatherTask {
@Autowired
private WeatherService weatherService;
// 每天凌晨3點(diǎn)更新天氣數(shù)據(jù)
@Scheduled(cron = "0 0 3 * * ?")
public void updateWeatherData() {
// 假設(shè)我們更新北京的天氣數(shù)據(jù),北京的城市編碼為110000
String adcode = "110000";
// 更新實(shí)時(shí)天氣
Live liveWeather = weatherService.getLiveWeather(adcode);
if (liveWeather != null) {
// 將實(shí)時(shí)天氣數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)或緩存中
System.out.println("實(shí)時(shí)天氣數(shù)據(jù)已更新:" + liveWeather);
}
// 更新未來(lái)幾天的天氣預(yù)報(bào)
List<WeatherForecast> forecastWeatherList = weatherService.getForecastWeather(adcode);
if (!forecastWeatherList.isEmpty()) {
// 將天氣預(yù)報(bào)數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)或緩存中
System.out.println("天氣預(yù)報(bào)數(shù)據(jù)已更新:" + forecastWeatherList);
}
}
}
(七)工具類(lèi)WeatherConstant和WeatherType
為了方便處理天氣數(shù)據(jù),創(chuàng)建WeatherConstant類(lèi)用于定義常量,WeatherType類(lèi)用于處理天氣類(lèi)型的映射。
WeatherConstant類(lèi)
package com.example.weather.common;
public class WeatherConstant {
public static final String SUCCESS = "1";
}
WeatherType類(lèi)
package com.example.weather.enums;
import lombok.Getter;
public enum WeatherType {
SUNNY("晴", "01"),
CLOUDY("多云", "02"),
OVERCAST("陰", "03"),
LIGHT_RAIN("小雨", "04"),
MODERATE_RAIN("中雨", "05"),
HEAVY_RAIN("大雨", "06"),
STORM("暴雨", "07"),
FOG("霧", "08"),
HAZE("霾", "09"),
SAND("沙塵暴", "10"),
WIND("大風(fēng)", "11"),
SNOW("雪", "12");
@Getter
private final String description;
@Getter
private final String code;
WeatherType(String description, String code) {
this.description = description;
this.code = code;
}
public static String getCodeByDes(String description) {
for (WeatherType type : WeatherType.values()) {
if (type.getDescription().equals(description)) {
return type.getCode();
}
}
return "";
}
}
四、測(cè)試與運(yùn)行
(一)啟動(dòng)項(xiàng)目
在IDE中運(yùn)行WeatherApplication類(lèi)的main方法,啟動(dòng)SpringBoot項(xiàng)目。
(二)測(cè)試接口
使用Postman或?yàn)g覽器訪問(wèn)以下接口進(jìn)行測(cè)試:
- 實(shí)時(shí)天氣接口:
http://localhost:8080/weather/live?adcode=110000 - 天氣預(yù)報(bào)接口:
http://localhost:8080/weather/forecast?adcode=110000
(三)查看定時(shí)任務(wù)
查看控制臺(tái)輸出,確認(rèn)定時(shí)任務(wù)是否正常運(yùn)行,天氣數(shù)據(jù)是否按時(shí)更新。
五、總結(jié)
通過(guò)本文的詳細(xì)步驟,我們成功地在SpringBoot項(xiàng)目中整合了高德地圖的天氣預(yù)報(bào)功能。從環(huán)境搭建到代碼實(shí)現(xiàn),再到定時(shí)任務(wù)的設(shè)置,每一步都清晰明確,確保大家能夠按照教程直接上手操作。在實(shí)際開(kāi)發(fā)中,可以根據(jù)需求進(jìn)一步優(yōu)化和擴(kuò)展功能,例如將天氣數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)中,或者為用戶(hù)提供更多城市的天氣查詢(xún)服務(wù)。
以上就是SpringBoot整合高德地圖實(shí)現(xiàn)天氣預(yù)報(bào)功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot高德地圖天氣預(yù)報(bào)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java 學(xué)習(xí)筆記(入門(mén)篇)_java的安裝與配置
學(xué)習(xí)Java已經(jīng)很長(zhǎng)時(shí)間了,由于基礎(chǔ)不好遇到問(wèn)題就無(wú)從下手,所以,打算寫(xiě)Java的隨手筆記來(lái)鞏固基礎(chǔ),加強(qiáng)學(xué)習(xí),接下來(lái)講解java的安裝,配置等,感興趣的朋友可以參考下2013-01-01
Springboot如何基于assembly服務(wù)化實(shí)現(xiàn)打包
這篇文章主要介紹了Springboot如何基于assembly服務(wù)化實(shí)現(xiàn)打包,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Java實(shí)現(xiàn)經(jīng)典游戲黃金礦工的示例代碼
《黃金礦工》游戲是一個(gè)經(jīng)典的抓金子小游戲,它可以鍛煉人的反應(yīng)能力。本文將用Java實(shí)現(xiàn)這一經(jīng)典的游戲,感興趣的小伙伴可以了解一下2022-02-02
java 動(dòng)態(tài)生成SQL的實(shí)例講解
下面小編就為大家?guī)?lái)一篇java 動(dòng)態(tài)生成SQL的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07
springmvc字符編碼過(guò)濾器CharacterEncodingFilter的使用
這篇文章主要介紹了springmvc字符編碼過(guò)濾器CharacterEncodingFilter的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2021-08-08
簡(jiǎn)述JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別
這篇文章主要介紹了JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07

