欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

一、前言

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

二、環(huán)境搭建

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

  • 使用Spring Initializr

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

(二)添加依賴

pom.xml文件中添加必要的依賴,確保項目能夠使用Spring Web和定時任務(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申請

  • 注冊高德開放平臺賬號

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

三、代碼實現(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,分別用于存儲實時天氣和預(yù)報天氣的數(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;
}

預(yù)報天氣實體類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類,用于調(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)絡(luò)等原因
        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);
    }

    /**
     * 獲取未來幾天的天氣預(yù)報
     *
     * @param adcode 城市編碼
     * @return 天氣預(yù)報列表
     */
    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)絡(luò)等原因
        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();
        }

        // 預(yù)報天氣
        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é)構(gòu)較為復(fù)雜,需要定義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)用服務(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;

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

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

(六)定時任務(wù)

為了定期更新天氣數(shù)據(jù),可以使用Spring的定時任務(wù)功能。創(chuàng)建WeatherTask類,設(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點更新天氣數(shù)據(jù)
    @Scheduled(cron = "0 0 3 * * ?")
    public void updateWeatherData() {
        // 假設(shè)我們更新北京的天氣數(shù)據(jù),北京的城市編碼為110000
        String adcode = "110000";

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

        // 更新未來幾天的天氣預(yù)報
        List<WeatherForecast> forecastWeatherList = weatherService.getForecastWeather(adcode);
        if (!forecastWeatherList.isEmpty()) {
            // 將天氣預(yù)報數(shù)據(jù)存儲到數(shù)據(jù)庫或緩存中
            System.out.println("天氣預(yù)報數(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("大風(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 "";
    }
}

四、測試與運行

(一)啟動項目

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

(二)測試接口

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

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

(三)查看定時任務(wù)

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

五、總結(jié)

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

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

相關(guān)文章

  • Java中i++與++i的區(qū)別和使用

    Java中i++與++i的區(qū)別和使用

    這篇文章主要介紹了Java中i++與++i的區(qū)別和使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • 部署springboot打包不打包配置文件,配置文件為外部配置文件使用詳解

    部署springboot打包不打包配置文件,配置文件為外部配置文件使用詳解

    在Spring Boot項目中,將配置文件排除在jar包之外,通過外部配置文件來管理不同環(huán)境的配置,可以實現(xiàn)靈活的配置管理,在pom.xml文件中添加相關(guān)配置,打包時忽略指定文件,運行時在jar包同級目錄下創(chuàng)建config文件夾,將配置文件放入其中即可
    2025-02-02
  • IDEA高效查看源碼的快捷鍵及小技巧

    IDEA高效查看源碼的快捷鍵及小技巧

    本篇文章這一部分的內(nèi)容主要為大家介紹了一些平時看源碼的時候常用的快捷鍵/小技巧!非常好用!掌握這些快捷鍵/小技巧,看源碼的效率提升一個等級
    2022-01-01
  • java基于雙向環(huán)形鏈表解決丟手帕問題的方法示例

    java基于雙向環(huán)形鏈表解決丟手帕問題的方法示例

    這篇文章主要介紹了java基于雙向環(huán)形鏈表解決丟手帕問題的方法,簡單描述了丟手帕問題,并結(jié)合實例形式給出了Java基于雙向環(huán)形鏈表解決丟手帕問題的步驟與相關(guān)操作技巧,需要的朋友可以參考下
    2017-11-11
  • Java 生成隨機驗證碼圖片的示例

    Java 生成隨機驗證碼圖片的示例

    這篇文章主要介紹了Java 生成隨機驗證碼圖片的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2020-10-10
  • Java本地方法(JNA)詳解及常見問題

    Java本地方法(JNA)詳解及常見問題

    JNA(Java?Native?Access)是一個開源Java框架,用于無需編寫JNI代碼即可動態(tài)訪問本地系統(tǒng)庫如Windows的dll,它允許Java程序直接調(diào)用本地方法,這篇文章主要介紹了Java本地方法(JNA)詳解及常見問題,需要的朋友可以參考下
    2024-09-09
  • 解決springcloud阿里云OSS文件訪問跨域問題的實現(xiàn)

    解決springcloud阿里云OSS文件訪問跨域問題的實現(xiàn)

    本文主要介紹了解決springcloud阿里云OSS文件訪問跨域問題的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • Java Http的基礎(chǔ)概念了解

    Java Http的基礎(chǔ)概念了解

    這篇文章主要介紹了Java Http的基礎(chǔ)概念,HTTP協(xié)議是建立在TCP協(xié)議之上的,這個程序是通過TCP編程來構(gòu)建一個簡單的Http服務(wù)器,需要的朋友可以參考下
    2023-04-04
  • 詳解JAVA 內(nèi)存管理

    詳解JAVA 內(nèi)存管理

    這篇文章主要介紹了JAVA 內(nèi)存管理的相關(guān)資料,文中講解非常細致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 使用SpringAOP獲取用戶操作日志入庫

    使用SpringAOP獲取用戶操作日志入庫

    這篇文章主要介紹了使用SpringAOP獲取用戶操作日志入庫,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11

最新評論