Springboot集成Dubbo:Hello Word

本文使用ZooKeeper提供协调服务。
dubbo主要分为服务提供者和服务消费者,服务提供者实现API、服务消费者调用API。

  • dubbo-interface: 提供公共API
  • dubbo-provider: 服务提供者
  • dubbo-consumer: 服务消费者

配置启动ZooKeeper

下载解压后,进入/conf复制zoo_sample.cfg并修改文件名为zoo.cfg

进入bin目录,双击启动zkServer.cmd

dubbo-interface

新建一个普通maven模块,并声明接口

public interface HelloService {
    String sayHello(String name);
}

然后打包到本地仓库

mvn install package

新建两个Springboot模块为dubbo-provider、dubbo-consumer

dubbo-provider

实现接口

import org.apache.dubbo.config.annotation.Service;
@Service // 暴露服务
public class HelloServiceImpl implements HelloService {
    @Override
    public String sayHello(String name) {
        return "Hello," + name;
    }
}

application.properties

dubbo.application.name=dubbo-provider
dubbo.registry.protocol=zookeeper
dubbo.registry.address=127.0.0.1:2181
dubbo.scan.base-packages=com.example.service

pom.xml

<!-- Springboot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
<!-- 公共服务API -->
<dependency>
    <groupId>org.example</groupId>
    <artifactId>dubbo-interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<!-- dubbo -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.5</version>
</dependency>
<!-- ZooKeeper客户端 -->
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.13.0</version>
</dependency>

dubbo-consumer

引用接口

@RestController
public class HelloController {
    @Reference
    private HelloService helloService;

    @RequestMapping("/hello")
    public String hello() {
        String hello = helloService.sayHello("world");
        System.out.println(helloService.sayHello("SnailClimb"));
        return hello;
    }
}

application.properties

server.port=8082
dubbo.application.name=dubbo-consumer
dubbo.registry.protocol=zookeeper
dubbo.registry.address=127.0.0.1:2181

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 公共服务API -->
<dependency>
    <groupId>org.example</groupId>
    <artifactId>dubbo-interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<!-- dubbo -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.5</version>
</dependency>
<!-- ZooKeeper客户端 -->
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.13.0</version>
</dependency>

依次启动dubbo-provider、dubbo-consumer,浏览器访问localhost:8082/hello查看运行接口

提供服务的两种配置方式

  1. 就是上面在application.properties里配置

    dubbo.scan.base-packages=com.example.service

  2. 在启动类上添加注解

    @EnableDubbo

这两种任选其一即可。

猜你喜欢

转载自www.cnblogs.com/dayfly/p/12631198.html
今日推荐