SpringBoot2.X整合集成Dubbo

环境安装

Dubbo使用zookeeper作为注册中心,首先要安装zookeeper。

Windows安装zookeeper如下:

https://blog.csdn.net/qq_33316784/article/details/88563482

Linux安装zookeeper如下:

https://www.cnblogs.com/expiator/p/9853378.html

SpringBoot新建项目

如果还不清楚怎么新建SpringBoot项目,可以参考: https://www.cnblogs.com/expiator/p/15844275.html

服务提供者Dubbo-provider

创建了dubbo-provider模块,作为服务提供者。

dubbo有多种groupId,其中的org.apache.dubbo的版本,比较适合SpringBoot2.X,注解不会过期或者失效。

引入 org.apache.dubbo 的包,dubbo的版本号设置在 2.7.5 。

pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>dubbo-provider</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>dubbo-provider</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.2.2.RELEASE</spring-boot.version>
        <dubbo.version>2.7.5</dubbo.version>
        <curator.version>4.2.0</curator.version>
        <zookeeper.version>3.4.12</zookeeper.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

	<!-- dubbo,注意要使用 org.apache.dubbo的groupId -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>${dubbo.version}</version>
        </dependency>

        <!-- zookeeper依赖 -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>${zookeeper.version}</version>
        </dependency>

        <!-- zookeeper的api管理依赖 -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>${curator.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <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>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
application.yml

在resources文件下添加 application.yml,配置如下:

dubbo:
  application:
    # 应用名称
    name: dubbo-provider
  protocol:
    # 协议名称
    name: dubbo
    # 协议端口
    port: 20880
  registry:
    # 注册中心地址
    address: zookeeper://127.0.0.1:2181

server:
  # 修改端口号,避免端口冲突
  port: 8081
pojo类:

@Data 是 lombok注解,相当于getter、setter、toString等方法。

@NoArgsConstructor也是 是 lombok注解,相当于没有参数的构造方法。

@AllArgsConstructor 是包含所有参数的构造方法。

如果不用lombok,也可以自行替换成相应的方法。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -4294369157631461921L;
    Long userId;
    String userName;
    String userInfo;
}
service:
public interface UserService {
    String getUserInfo();

    User getUserById(String userId);
}

service实现类:

注意,@service注解,引入的包是org.apache.dubbo.config.annotation.Service

import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

/**
 * 注意,@service注解,引入的包是org.apache.dubbo.config.annotation.Service
 */
@Service
@Component
public class UserServiceImpl implements UserService {

    @Override
    public String getUserInfo() {
        return "userTest";
    }

    @Override
    public User getUserById(String userId) {
        User user = new User();
        user.setUserId(Long.valueOf(userId));
        user.setUserInfo("test");
        user.setUserName("lin");
        return user;
    }

}

SpringBoot启动类:

注意:

/**
 * 提供服务的应用配置DubboComponentScan注解,指定扫描的service所在的文件
 */
@SpringBootApplication
@DubboComponentScan("com.example.service")
public class DubboProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(DubboProviderApplication.class, args);
    }

}

install服务提供者dubbo-provider

在idea中,对服务提供者dubbo-provider的依赖, 用Maven执行clean,并install到Maven仓库,就可以提供给其他模块使用。

服务消费者 dubbo-consumer

新建一个服务消费者 dubbo-consumer的maven项目。

pom.xml

pom.xml中,服务消费者 dubbo-consumer 的依赖跟之前的类似,只是还要引入服务提供者dubbo-provider的依赖,这样才能调用其中的Service。

<!-- 引入服务提供者的依赖,注意版本号 -->
<dependency>
	<groupId>com.example</groupId>
	<artifactId>dubbo-provider</artifactId>
	<version>1.0-SNAPSHOT</version>
</dependency>
application.yml

类似 dubbo-provider, 可以将端口号修改为 8082,避免端口号冲突

ConsumerController 类:
import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class ConsumerController {
    /**
     * 通过 @Reference注解调用远程服务,也就是服务提供者dubbo-provider的服务
     */
    @Reference
    private UserService userService;


    @GetMapping("/info")
    public String getUserById() {
        return userService.getUserInfo();
    }


    @GetMapping("/{id}")
    public User getUserById(@PathVariable String id) {
        return userService.getUserById(id);
    }

}
DubboConsumerApplication启动类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DubboConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DubboConsumerApplication.class, args);
    }
}

启动项目

没有启动 zookeeper会报错:

Caused by: java.lang.IllegalStateException: zookeeper not connected
	at org.apache.dubbo.remoting.zookeeper.curator.CuratorZookeeperClient.<init>(CuratorZookeeperClient.java:80) ~[dubbo-2.7.5.jar:2.7.5]
	... 32 common frames omitted
  • 端口号被占用,需要修改端口号,否则会报错。

    Web server failed to start. Port 8080 was already in use.
    Action:
    Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

  • 启动报错:

    Whitelabel Error Page
    This application has no explicit mapping for /error, so you are seeing this as a fallback.

解决方法:https://www.cnblogs.com/expiator/p/15837518.html

  • 先启动Provider,再启动Consumer

启动成功如下:

参考资料:

https://www.jb51.net/article/178946.htm

相关推荐
齐 飞17 分钟前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
狂放不羁霸25 分钟前
idea | 搭建 SpringBoot 项目之配置 Maven
spring boot·maven·intellij-idea
九圣残炎26 分钟前
【从零开始的LeetCode-算法】1456. 定长子串中元音的最大数目
java·算法·leetcode
wclass-zhengge28 分钟前
Netty篇(入门编程)
java·linux·服务器
LunarCod34 分钟前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发
计算机学长felix1 小时前
基于SpringBoot的“校园交友网站”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·毕业设计·交友
Re.不晚1 小时前
Java入门15——抽象类
java·开发语言·学习·算法·intellij-idea
雷神乐乐1 小时前
Maven学习——创建Maven的Java和Web工程,并运行在Tomcat上
java·maven
码农派大星。1 小时前
Spring Boot 配置文件
java·spring boot·后端
顾北川_野1 小时前
Android 手机设备的OEM-unlock解锁 和 adb push文件
android·java