logo
1
0
WeChat Login
实战项目:天气API服务库和命令行应用 - 添加weather-api和weather-app模块 - 演示Maven依赖管理和Gradle构建 - 包含完整文档和运行脚本

Weather API 天气服务库

这是一个简单的Kotlin天气服务库,提供了获取全球城市天气信息的API接口。该库支持通过城市名称或地理坐标查询当前天气状况。

功能特性

  • 通过城市名称查询天气
  • 通过地理坐标查询天气
  • 支持真实天气API (WeatherStack)
  • 提供模拟天气数据用于开发测试
  • 使用Kotlin协程实现异步操作

如何使用

添加依赖

将库添加到你的项目中:

Gradle (Kotlin DSL)

// build.gradle.kts repositories { mavenLocal() // 添加本地Maven仓库 mavenCentral() } dependencies { implementation("com.example:weather-api:1.0.0") }

Gradle (Groovy)

// build.gradle repositories { mavenLocal() // 添加本地Maven仓库 mavenCentral() } dependencies { implementation 'com.example:weather-api:1.0.0' }

Maven

<dependency> <groupId>com.example</groupId> <artifactId>weather-api</artifactId> <version>1.0.0</version> </dependency>

代码示例

import com.example.weatherapi.WeatherServiceFactory import kotlinx.coroutines.runBlocking fun main() { // 获取模拟的天气服务 val weatherService = WeatherServiceFactory.createMockWeatherService() // 或者使用真实的WeatherStack API (需要注册获取API密钥) // val weatherService = WeatherServiceFactory.createWeatherStackService("YOUR_API_KEY") runBlocking { // 通过城市名称查询 val weatherResult = weatherService.getCurrentWeather("beijing") weatherResult.onSuccess { weatherData -> println("城市: ${weatherData.location.name}") println("温度: ${weatherData.current.temperature}°C") println("天气: ${weatherData.current.weather_descriptions.joinToString()}") }.onFailure { error -> println("查询失败: ${error.message}") } // 通过坐标查询 val coordinatesResult = weatherService.getCurrentWeatherByCoordinates(51.5074, -0.1278) coordinatesResult.onSuccess { weatherData -> println("查询到的城市: ${weatherData.location.name}") } } }

构建项目

前提条件

  • JDK 8 或更高版本
  • Gradle 7.0 或更高版本

构建步骤

  1. 克隆项目
  2. 进入项目目录
  3. 执行Gradle构建命令
./gradlew :modules:weather-api:build

运行测试

./gradlew :modules:weather-api:test

发布到本地Maven仓库

要将库发布到本地Maven仓库,请执行以下命令:

./gradlew :modules:weather-api:publishToMavenLocal

发布后,该库将可在本地Maven仓库中使用(通常位于~/.m2/repository/com/example/weather-api/1.0.0/)。

切换应用程序使用本地Maven库

在完成发布后,你可以修改应用程序的构建文件,从直接依赖项目改为使用Maven仓库中的库:

// 从这个 implementation(project(":modules:weather-api")) // 改为这个 implementation("com.example:weather-api:1.0.0")

模块结构

modules/weather-api/ ├── src/ │ ├── main/ │ │ └── kotlin/ │ │ └── com/ │ │ └── example/ │ │ └── weatherapi/ │ │ ├── WeatherService.kt // 服务接口 │ │ ├── WeatherServiceFactory.kt // 工厂类 │ │ ├── impl/ │ │ │ ├── MockWeatherService.kt // 模拟实现 │ │ │ └── WeatherStackService.kt // 真实API实现 │ │ └── model/ │ │ └── WeatherData.kt // 数据模型 │ └── test/ │ └── kotlin/ │ └── com/ │ └── example/ │ └── weatherapi/ │ └── MockWeatherServiceTest.kt // 测试类 └── build.gradle.kts // 构建配置

注意事项

  • 对于真实天气API (WeatherStack),你需要在官网注册获取免费API密钥
  • 模拟实现提供了固定的城市列表,仅用于开发和测试
  • 本库使用了Kotlin协程,所有API调用都是挂起函数,需要在协程作用域内调用