Dubbo(97)如何在物联网系统中应用Dubbo?

在物联网系统中应用Dubbo,可以通过以下步骤实现:

  1. 项目结构设计:规划项目的模块结构,通常包括服务接口模块、各个服务提供者模块(如设备管理服务、数据采集服务、数据分析服务等)、服务消费者模块(如前端应用、后台管理系统等)。
  2. 服务接口定义:定义各个服务的接口,确保服务提供者和消费者能够共享相同的接口。
  3. 服务提供者实现:实现各个服务接口,并配置Dubbo提供服务。
  4. 服务消费者调用:在服务消费者中引用服务接口,并通过Dubbo调用远程服务。
  5. 服务注册与发现:配置注册中心(如Zookeeper)以实现服务注册与发现。
  6. 配置管理:管理项目的配置文件,确保服务提供者和消费者能够正确连接到注册中心并发现彼此。
  7. 测试与部署:测试服务的调用,确保服务能够正常工作,并将服务部署到生产环境。

以下是一个详细的示例,展示如何在物联网系统中应用Dubbo。

1. 项目结构设计

我们将创建一个包含多个模块的项目:dubbo-apidevice-management-servicedata-collection-servicedata-analysis-servicefrontend-application

iot-system
├── dubbo-api
│   └── src/main/java/com/example/dubbo/api
│       ├── DeviceManagementService.java
│       ├── DataCollectionService.java
│       └── DataAnalysisService.java
├── device-management-service
│   └── src/main/java/com/example/devicemanagement
│       ├── service
│       │   └── DeviceManagementServiceImpl.java
│       ├── config
│       │   └── DubboProviderConfig.java
│       └── DeviceManagementServiceApplication.java
├── data-collection-service
│   └── src/main/java/com/example/datacollection
│       ├── service
│       │   └── DataCollectionServiceImpl.java
│       ├── config
│       │   └── DubboProviderConfig.java
│       └── DataCollectionServiceApplication.java
├── data-analysis-service
│   └── src/main/java/com/example/dataanalysis
│       ├── service
│       │   └── DataAnalysisServiceImpl.java
│       ├── config
│       │   └── DubboProviderConfig.java
│       └── DataAnalysisServiceApplication.java
├── frontend-application
│   └── src/main/java/com/example/frontend
│       ├── controller
│       │   └── IotController.java
│       ├── config
│       │   └── DubboConsumerConfig.java
│       └── FrontendApplication.java
└── pom.xml

2. 服务接口定义

2.1 创建 dubbo-api 模块

创建 dubbo-api 模块的 pom.xml 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/POM/4.0.0 http://www.w3.org/2001/04/xmldsig-more#">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>dubbo-api</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.7.8</version>
        </dependency>
    </dependencies>
</project>
2.2 定义服务接口

dubbo-api/src/main/java/com/example/dubbo/api 目录下创建 DeviceManagementServiceDataCollectionServiceDataAnalysisService 接口:

package com.example.dubbo.api;

public interface DeviceManagementService {
    String registerDevice(String deviceId, String deviceType);
    String getDeviceStatus(String deviceId);
}

public interface DataCollectionService {
    String collectData(String deviceId, String data);
}

public interface DataAnalysisService {
    String analyzeData(String data);
}

3. 服务提供者实现

3.1 创建 device-management-service 模块

创建 device-management-service 模块的 pom.xml 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/POM/4.0.0 http://www.w3.org/2001/04/xmldsig-more#">

    <parent>
        <groupId>com.example</groupId>
        <artifactId>iot-system</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>device-management-service</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>dubbo-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.7.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>
</project>
3.2 实现设备管理服务接口

device-management-service/src/main/java/com/example/devicemanagement/service 目录下创建 DeviceManagementServiceImpl 类:

package com.example.devicemanagement.service;

import com.example.dubbo.api.DeviceManagementService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@DubboService
public class DeviceManagementServiceImpl implements DeviceManagementService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceManagementServiceImpl.class);

    @Override
    public String registerDevice(String deviceId, String deviceType) {
        logger.info("Registering device ID: {}, Type: {}", deviceId, deviceType);
        return "Device " + deviceId + " of type " + deviceType + " registered successfully.";
    }

    @Override
    public String getDeviceStatus(String deviceId) {
        logger.info("Getting status for device ID: {}", deviceId);
        return "Status of device " + deviceId + ": Active";
    }
}
3.3 配置Dubbo服务

device-management-service/src/main/java/com/example/devicemanagement/config 目录下创建 DubboProviderConfig 类:

package com.example.devicemanagement.config;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableDubbo(scanBasePackages = "com.example.devicemanagement.service")
public class DubboProviderConfig {
}
3.4 创建启动类

device-management-service/src/main/java/com/example/devicemanagement 目录下创建 DeviceManagementServiceApplication 类:

package com.example.devicemanagement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DeviceManagementServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(DeviceManagementServiceApplication.class, args);
    }
}
3.5 配置文件

device-management-service/src/main/resources 目录下创建 application.yml 配置文件:

spring:
  application:
    name: device-management-service
  main:
    web-application-type: none

dubbo:
  application:
    name: device-management-service
  registry:
    address: zookeeper://localhost:2181
  protocol:
    name: dubbo
    port: 20880
  scan:
    base-packages: com.example.devicemanagement.service

logging:
  level:
    com.example.devicemanagement: INFO
  file:
    name: logs/device-management-service.log
3.6 创建 data-collection-service 模块

创建 data-collection-service 模块的 pom.xml 文件,类似于 device-management-service 模块。

3.7 实现数据采集服务接口

data-collection-service/src/main/java/com/example/datacollection/service 目录下创建 DataCollectionServiceImpl 类:

package com.example.datacollection.service;

import com.example.dubbo.api.DataCollectionService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@DubboService
public class DataCollectionServiceImpl implements DataCollectionService {
    private static final Logger logger = LoggerFactory.getLogger(DataCollectionServiceImpl.class);

    @Override
    public String collectData(String deviceId, String data) {
        logger.info("Collecting data from device ID: {}, Data: {}", deviceId, data);
        return "Collected data from device " + deviceId + ": " + data;
    }
}
3.8 配置Dubbo服务和启动类

data-collection-service 模块中配置Dubbo服务和启动类,类似于 device-management-service 模块。

3.9 创建 data-analysis-service 模块

创建 data-analysis-service 模块的 pom.xml 文件,类似于 device-management-service 模块。

3.10 实现数据分析服务接口

data-analysis-service/src/main/java/com/example/dataanalysis/service 目录下创建 DataAnalysisServiceImpl 类:

package com.example.dataanalysis.service;

import com.example.dubbo.api.DataAnalysisService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@DubboService
public class DataAnalysisServiceImpl implements DataAnalysisService {
    private static final Logger logger = LoggerFactory.getLogger(DataAnalysisServiceImpl.class);

    @Override
    public String analyzeData(String data) {
        logger.info("Analyzing data: {}", data);
        return "Analyzed data: " + data;
    }
}
3.11 配置Dubbo服务和启动类

data-analysis-service 模块中配置Dubbo服务和启动类,类似于 device-management-service 模块。

4. 服务消费者调用

4.1 创建 frontend-application 模块

创建 frontend-application 模块的 pom.xml 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/POM/4.0.0 http://www.w3.org/2001/04/xmldsig-more#">

    <parent>
        <groupId>com.example</groupId>
        <artifactId>iot-system</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>frontend-application</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>dubbo-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.7.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>
</project>
4.2 创建控制器

frontend-application/src/main/java/com/example/frontend/controller 目录下创建 IotController 类:

package com.example.frontend.controller;

import com.example.dubbo.api.DataCollectionService;
import com.example.dubbo.api.DataAnalysisService;
import com.example.dubbo.api.DeviceManagementService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IotController {
    private static final Logger logger = LoggerFactory.getLogger(IotController.class);

    @DubboReference
    private DeviceManagementService deviceManagementService;

    @DubboReference
    private DataCollectionService dataCollectionService;

    @DubboReference
    private DataAnalysisService dataAnalysisService;

    @GetMapping("/registerDevice")
    public String registerDevice(@RequestParam String deviceId, @RequestParam String deviceType) {
        logger.info("Registering device ID: {}, Type: {}", deviceId, deviceType);
        return deviceManagementService.registerDevice(deviceId, deviceType);
    }

    @GetMapping("/getDeviceStatus")
    public String getDeviceStatus(@RequestParam String deviceId) {
        logger.info("Getting status for device ID: {}", deviceId);
        return deviceManagementService.getDeviceStatus(deviceId);
    }

    @GetMapping("/collectData")
    public String collectData(@RequestParam String deviceId, @RequestParam String data) {
        logger.info("Collecting data from device ID: {}, Data: {}", deviceId, data);
        return dataCollectionService.collectData(deviceId, data);
    }

    @GetMapping("/analyzeData")
    public String analyzeData(@RequestParam String data) {
        logger.info("Analyzing data: {}", data);
        return dataAnalysisService.analyzeData(data);
    }
}
4.3 配置Dubbo消费

frontend-application/src/main/java/com/example/frontend/config 目录下创建 DubboConsumerConfig 类:

package com.example.frontend.config;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableDubbo(scanBasePackages = "com.example.frontend.controller")
public class DubboConsumerConfig {
}
4.4 创建启动类

frontend-application/src/main/java/com/example/frontend 目录下创建 FrontendApplication 类:

package com.example.frontend;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FrontendApplication {
    public static void main(String[] args) {
        SpringApplication.run(FrontendApplication.class, args);
    }
}
4.5 配置文件

frontend-application/src/main/resources 目录下创建 application.yml 配置文件:

spring:
  application:
    name: frontend-application

dubbo:
  application:
    name: frontend-application
  registry:
    address: zookeeper://localhost:2181
  protocol:
    name: dubbo
  scan:
    base-packages: com.example.frontend.controller

logging:
  level:
    com.example.frontend: INFO
  file:
    name: logs/frontend-application.log

5. 根项目的 pom.xml

在根项目 iot-system 中创建 pom.xml 文件,定义模块和依赖管理:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/POM/4.0.0 http://www.w3.org/2001/04/xmldsig-more#">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>iot-system</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>dubbo-api</module>
        <module>device-management-service</module>
        <module>data-collection-service</module>
        <module>data-analysis-service</module>
        <module>frontend-application</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo</artifactId>
                <version>2.7.8</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-spring-boot-starter</artifactId>
                <version>2.7.8</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>2.3.4.RELEASE</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

6. 启动Zookeeper

确保Zookeeper在本地运行,默认端口为 2181。可以通过下载Zookeeper并运行以下命令启动Zookeeper:

bin/zkServer.sh start

7. 启动服务提供者和消费者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辞暮尔尔-烟火年年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值