最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合高德地圖實現(xiàn)天氣預報功能

 更新時間:2025年03月26日 11:25:14   作者:全干程序員demo  
在當今數(shù)字化時代,天氣預報功能在眾多應用中扮演著重要角色,通過整合高德地圖提供的天氣API,我們可以輕松地在自己的SpringBoot項目中實現(xiàn)這一功能,本文將詳細介紹如何在SpringBoot項目中整合高德地圖的天氣預報功能,感興趣的小伙伴跟著小編一起來看看吧

一、前言

在當今數(shù)字化時代,天氣預報功能在眾多應用中扮演著重要角色。通過整合高德地圖提供的天氣API,我們可以輕松地在自己的SpringBoot項目中實現(xiàn)這一功能,為用戶提供實時和未來幾天的天氣信息。本文將詳細介紹如何在SpringBoot項目中整合高德地圖的天氣預報功能,包括環(huán)境搭建、代碼實現(xiàn)、定時任務設置等關鍵步驟,確保大家能夠按照教程成功實現(xiàn)功能。

二、環(huán)境搭建

(一)創(chuàng)建SpringBoot項目

  • 使用Spring Initializr

    • 訪問 Spring Initializr 網(wǎng)站。
    • 選擇項目元數(shù)據(jù),如項目名稱、包名等。
    • 添加依賴:Spring WebSpring Boot DevTools(可選,方便開發(fā)時熱部署)。
    • 點擊“Generate”按鈕下載項目壓縮包,解壓后導入到你的IDE(如IntelliJ IDEA或Eclipse)中。
  • 項目結(jié)構示例

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

(二)添加依賴

pom.xml文件中添加必要的依賴,確保項目能夠使用Spring Web和定時任務等功能。

<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申請

  • 注冊高德開放平臺賬號

    • 訪問 高德開放平臺 官網(wǎng),注冊賬號并登錄。
    • 在“控制臺”中創(chuà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

三、代碼實現(xiàn)

(一)配置類

創(chuàng)建一個配置類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;
}

(二)實體類

定義兩個實體類LiveWeatherForecast,分別用于存儲實時天氣和預報天氣的數(shù)據(jù)。

實時天氣實體類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;
}

預報天氣實體類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;
}

(三)服務層

創(chuàng)建WeatherService類,用于調(diào)用高德地圖的天氣API,并將返回的數(shù)據(jù)封裝到實體類中。

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;

    /**
     * 獲取實時天氣
     *
     * @param adcode 城市編碼
     * @return 實時天氣實體類
     */
    public Live getLiveWeather(String adcode) {
        String sendUrl = amapWeatherConfig.getWeatherurl() +
                "?key=" + amapWeatherConfig.getKey() +
                "&city=" + adcode +
                "&extensions=base";
        ResponseEntity<GaoDeResult> responseEntity = restTemplate.getForEntity(sendUrl, GaoDeResult.class);
        // 請求異常,可能由于網(wǎng)絡等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Gaode interface error");
            return null;
        }
        // 請求失敗
        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;
        }
        // 實況天氣
        return lives.get(0);
    }

    /**
     * 獲取未來幾天的天氣預報
     *
     * @param adcode 城市編碼
     * @return 天氣預報列表
     */
    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);
        // 請求異常,可能由于網(wǎng)絡等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Gaode interface error");
            return Collections.emptyList();
        }

        // 請求失敗
        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();
        }

        // 預報天氣
        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;
    }
}

(四)實體類GaoDeResult和Forecast

高德地圖API返回的數(shù)據(jù)結(jié)構較為復雜,需要定義GaoDeResultForecast類來接收和處理這些數(shù)據(jù)。

GaoDeResult

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

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類,用于處理前端請求,并調(diào)用服務層的方法獲取天氣數(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;

    /**
     * 獲取實時天氣
     *
     * @param adcode 城市編碼
     * @return 實時天氣數(shù)據(jù)
     */
    @GetMapping("/live")
    public Live getLiveWeather(@RequestParam String adcode) {
        return weatherService.getLiveWeather(adcode);
    }

    /**
     * 獲取未來幾天的天氣預報
     *
     * @param adcode 城市編碼
     * @return 天氣預報數(shù)據(jù)
     */
    @GetMapping("/forecast")
    public List<WeatherForecast> getForecastWeather(@RequestParam String adcode) {
        return weatherService.getForecastWeather(adcode);
    }
}

(六)定時任務

為了定期更新天氣數(shù)據(jù),可以使用Spring的定時任務功能。創(chuàng)建WeatherTask類,設置定時任務。

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點更新天氣數(shù)據(jù)
    @Scheduled(cron = "0 0 3 * * ?")
    public void updateWeatherData() {
        // 假設我們更新北京的天氣數(shù)據(jù),北京的城市編碼為110000
        String adcode = "110000";

        // 更新實時天氣
        Live liveWeather = weatherService.getLiveWeather(adcode);
        if (liveWeather != null) {
            // 將實時天氣數(shù)據(jù)存儲到數(shù)據(jù)庫或緩存中
            System.out.println("實時天氣數(shù)據(jù)已更新:" + liveWeather);
        }

        // 更新未來幾天的天氣預報
        List<WeatherForecast> forecastWeatherList = weatherService.getForecastWeather(adcode);
        if (!forecastWeatherList.isEmpty()) {
            // 將天氣預報數(shù)據(jù)存儲到數(shù)據(jù)庫或緩存中
            System.out.println("天氣預報數(shù)據(jù)已更新:" + forecastWeatherList);
        }
    }
}

(七)工具類WeatherConstant和WeatherType

為了方便處理天氣數(shù)據(jù),創(chuàng)建WeatherConstant類用于定義常量,WeatherType類用于處理天氣類型的映射。

WeatherConstant

package com.example.weather.common;

public class WeatherConstant {
    public static final String SUCCESS = "1";
}

WeatherType

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("大風", "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 "";
    }
}

四、測試與運行

(一)啟動項目

在IDE中運行WeatherApplication類的main方法,啟動SpringBoot項目。

(二)測試接口

使用Postman或瀏覽器訪問以下接口進行測試:

  • 實時天氣接口http://localhost:8080/weather/live?adcode=110000
  • 天氣預報接口http://localhost:8080/weather/forecast?adcode=110000

(三)查看定時任務

查看控制臺輸出,確認定時任務是否正常運行,天氣數(shù)據(jù)是否按時更新。

五、總結(jié)

通過本文的詳細步驟,我們成功地在SpringBoot項目中整合了高德地圖的天氣預報功能。從環(huán)境搭建到代碼實現(xiàn),再到定時任務的設置,每一步都清晰明確,確保大家能夠按照教程直接上手操作。在實際開發(fā)中,可以根據(jù)需求進一步優(yōu)化和擴展功能,例如將天氣數(shù)據(jù)存儲到數(shù)據(jù)庫中,或者為用戶提供更多城市的天氣查詢服務。

以上就是SpringBoot整合高德地圖實現(xiàn)天氣預報功能的詳細內(nèi)容,更多關于SpringBoot高德地圖天氣預報的資料請關注腳本之家其它相關文章!

相關文章

  • 深入聊聊Java內(nèi)存泄露問題

    深入聊聊Java內(nèi)存泄露問題

    所謂內(nèi)存泄露就是指一個不再被程序使用的對象或變量一直被占據(jù)在內(nèi)存中,下面這篇文章主要給大家介紹了關于Java內(nèi)存泄露問題的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • java 學習筆記(入門篇)_java的安裝與配置

    java 學習筆記(入門篇)_java的安裝與配置

    學習Java已經(jīng)很長時間了,由于基礎不好遇到問題就無從下手,所以,打算寫Java的隨手筆記來鞏固基礎,加強學習,接下來講解java的安裝,配置等,感興趣的朋友可以參考下
    2013-01-01
  • Java中scheduleAtFixedRate的用法

    Java中scheduleAtFixedRate的用法

    如何正確使用Java中的scheduleAtFixedRate是一篇介紹Java中定時任務調(diào)度器的文章。它詳細介紹了scheduleAtFixedRate方法的用法、參數(shù)及作用,并給出了一些實例以幫助讀者更好地理解其使用。本文為Java開發(fā)人員提供了一些實用的技巧,幫助他們更好地管理和控制定時任務
    2023-04-04
  • Java中四種引用詳解

    Java中四種引用詳解

    這篇文章主要為大家介紹了Java中的四種引用,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-12-12
  • Springboot如何基于assembly服務化實現(xiàn)打包

    Springboot如何基于assembly服務化實現(xiàn)打包

    這篇文章主要介紹了Springboot如何基于assembly服務化實現(xiàn)打包,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • Java實現(xiàn)經(jīng)典游戲黃金礦工的示例代碼

    Java實現(xiàn)經(jīng)典游戲黃金礦工的示例代碼

    《黃金礦工》游戲是一個經(jīng)典的抓金子小游戲,它可以鍛煉人的反應能力。本文將用Java實現(xiàn)這一經(jīng)典的游戲,感興趣的小伙伴可以了解一下
    2022-02-02
  • java 動態(tài)生成SQL的實例講解

    java 動態(tài)生成SQL的實例講解

    下面小編就為大家?guī)硪黄猨ava 動態(tài)生成SQL的實例講解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • SpringBoot整合jasypt加密配置文件敏感信息

    SpringBoot整合jasypt加密配置文件敏感信息

    在項目中我們需要對配置文件的一些敏感信息進行加密處理,比如數(shù)據(jù)庫賬戶密碼,避免直接暴露出來,這種場景常常用于生產(chǎn)環(huán)境,我們不想讓開發(fā)人員知道生產(chǎn)庫的密碼,有運維人員統(tǒng)一管理,所以本文給大家介紹了SpringBoot整合jasypt加密配置文件敏感信息
    2024-06-06
  • springmvc字符編碼過濾器CharacterEncodingFilter的使用

    springmvc字符編碼過濾器CharacterEncodingFilter的使用

    這篇文章主要介紹了springmvc字符編碼過濾器CharacterEncodingFilter的使用,具有很好的參考價值,希望對大家有所幫助。
    2021-08-08
  • 簡述JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別

    簡述JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別

    這篇文章主要介紹了JAVA中堆內(nèi)存與棧內(nèi)存的區(qū)別,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07

最新評論

白银市| 长治县| 临夏市| 五家渠市| 陆川县| 涞源县| 金川县| 手机| 平潭县| 三台县| 察隅县| 镇安县| 吉木乃县| 逊克县| 乐陵市| 宁阳县| 蕉岭县| 宿松县| 义乌市| 抚顺县| 嘉兴市| 清原| 天峨县| 夏津县| 苍梧县| 洪泽县| 吴忠市| 安仁县| 遵化市| 赤壁市| 玛曲县| 广东省| 贵阳市| 沧州市| 抚顺市| 广宗县| 云安县| 江川县| 祁东县| 吴堡县| 南郑县|