专栏首页Java后端技术栈cwnaitDubbo的两种常规启动方式

Dubbo的两种常规启动方式

本案例是dubbo版本:2.7.4.1 org.apache.dubbo

建一个工程为dubbo-demo,再创建三个module

dubbo-user-api
dubbo-user-provider
dubbo-user-consumer

dubbo-user-api

DemoService.java接口

package com.tian.dubbo.service;

public interface DemoService {
    String test(String string);
}

然后打成jar给dubbo-user-providerdubbo-user-consumer使用

mvn clean install

dubbo-user-api.jar

启动zookeeper

本地启动一个zookeepeer,作为dubbo的注册中心,(dubbo推荐zookeeper为注册中心)

dubbo-user-provider

pom.xml中添加

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <dubbo.version>2.5.3</dubbo.version>
        <spring.version>4.3.6.RELEASE</spring.version>
        <java.version>1.8</java.version>
        <log4j.version>1.2.17</log4j.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.7.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-dependencies-zookeeper</artifactId>
            <version>2.7.4.1</version>
        </dependency>
        <dependency>
            <artifactId>dubbo-user-api</artifactId>
            <groupId>com.tian.dubbo</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

创建一个DemoServiceImpl.java

public class DemoServiceImpl implements DemoService {
    @Override
    public String test(String msg) {
        System.out.println("接收到参数:" + msg);
        return "provider:" + msg;
    }
}

创建启动类ProviderApplication.java

public class ProviderApplication {
    private static String zookeeperHost = System.getProperty("zookeeper.address", "127.0.0.1");

    public static void main(String[] args) throws Exception {
        ServiceConfig<DemoService> service = new ServiceConfig<>();
        service.setApplication(new ApplicationConfig("first-dubbo-provider"));
        service.setRegistry(new RegistryConfig("zookeeper://" + zookeeperHost + ":2181"));
        service.setInterface(DemoService.class);
        service.setRef(new DemoServiceImpl());
        service.export();
        System.out.println("Dubbo server started");
        new CountDownLatch(1).await();
    }
}

启动

输出:Dubbo server started

启动成功,等着消费方调用。下面来说说消费方

dubbo-user-consumer

pom.xml添加

 <properties>
        <dubbo.version>2.5.3</dubbo.version>
        <spring.version>4.3.6.RELEASE</spring.version>
        <java.version>1.8</java.version>
        <log4j.version>1.2.17</log4j.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.7.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-dependencies-zookeeper</artifactId>
            <version>2.7.4.1</version>
        </dependency>
        <dependency>
            <artifactId>dubbo-user-api</artifactId>
            <groupId>com.tian.dubbo</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
    </dependencies>

启动类ConsumerApplication.java

启动并调用

输出:provider:dubbo

dubbo-user-provider中输出:接收到参数:dubbo

xml方式

provider

provider.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="provider"/>
    <!-- 使用zookeeper注册中心暴露服务地址 -->
    <dubbo:registry address="zookeeper://localhost:2181" protocol="zookeeper" check="false"/>
    <!-- 用dubbo协议在随机端口暴露服务 -->
    <dubbo:protocol id="dubbo" name="dubbo" port="-1" threads="200" />
    <!-- 声明需要暴露的服务接口 -->
    <dubbo:service interface="com.tian.dubbo.service.DemoService" ref="demoService"/>
    <!-- 和本地bean一样实现服务 -->
    <bean id="demoService" class="com.tian.dubbo.service.impl.DemoServiceImpl"/>
</beans>

启动类ProviderApplication.java

public class ProviderApplication {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new          
                   ClassPathXmlApplicationContext("provider.xml");
        System.err.println(context.getDisplayName() + ": here");
        context.start();
        System.err.println("服务已经启动...");
        System.in.read();
    }
}

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %t %5p %c{2}: %m%n" />
        </layout>
    </appender>
    <root>
        <level value="INFO" />
        <appender-ref ref="CONSOLE" />
    </root>
</log4j:configuration>

启动输出:

consumer

ConsumerApplication.java

public class ConsumerApplication {
  public static void main(String[] args) {
      //测试常规服务
      ClassPathXmlApplicationContext context =
              new ClassPathXmlApplicationContext("consumer.xml");
      context.start();
      System.err.println("consumer start");
      DemoService demoService = context.getBean(DemoService.class);
      System.out.println(demoService.test("dubbo xml"));
  }
}

consumer.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    <dubbo:application name="demotest-consumer" owner="programmer" organization="dubbox"/>
    <!--向 zookeeper 订阅 provider 的地址,由 zookeeper 定时推送-->
    <dubbo:registry address="zookeeper://localhost:2181"/>
    <!--使用 dubbo 协议调用定义好的 api.PermissionService 接口-->
    <dubbo:reference id="demoService" interface="com.tian.dubbo.service.DemoService"/>
</beans>

log4j.xml

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %t %5p %c{2}: %m%n" />
        </layout>
    </appender>
    <root>
        <level value="INFO" />
        <appender-ref ref="CONSOLE" />
    </root>
</log4j:configuration>

启动输出:

证明调用成功,再看provider的输出

自此,一个xml版本的dubbo demo搞定。

注解方式

provider

DemoServiceImpl.java中的@Service使用的是org.apache.dubbo下面的

import com.tian.dubbo.service.DemoService;
import org.apache.dubbo.config.annotation.Service;
@Service
public class DemoServiceImpl implements DemoService {
    @Override
    public String test(String msg) {
        System.out.println("接收到参数:" + msg);
        return "provider:" + msg;
    }
}

启动类

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;

@Configuration
@EnableDubbo(scanBasePackages = "com.tian.dubbo.service.impl")//扫描添加了@Service的注解
@PropertySource("classpath:dubbo-provider.properties")//配置文件的扫描
public class ProviderApplication {
    
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new 
             AnnotationConfigApplicationContext(ProviderApplication.class);
        context.start();
        System.err.println("服务已经启动...");
        System.in.read(); //需要等待
    }
}

dubbo-provider.properties

dubbo.application.name=annotation-provider
dubbo.registry.address=zookeeper://localhost:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880

启动

consumer

dubbo-consumer.properties

dubbo.application.name=annotation-consumer
dubbo.registry.address=zookeeper://localhost:2181
dubbo.consumer.timeout=3000
import com.tian.dubbo.service.DemoService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@EnableDubbo(scanBasePackages = "com.tian.dubbo")//启用Dubbo扫描并注入对象
@PropertySource("classpath:dubbo-consumer.properties")//扫描配置文件
public class ConsumerApplication {
    
    //这里需要使用Dubbo来进行注入
    @Reference
    DemoService demoService;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new 
            AnnotationConfigApplicationContext(ConsumerApplication.class);
        ConsumerApplication customer = context.getBean(ConsumerApplication.class);
        String say = customer.demoService.test("dubbo annotation");
        System.out.println(say);
    }
}

启动

调用成功。

本文分享自微信公众号 - Java后端技术栈(t-j20120622),作者:田先生

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-12-18

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Springboot实战--助你工作更顺心

    主要介绍 Spring Boot 在项目中最常使用的功能点,旨在带领学习者快速掌握 Spring Boot 在开发时需要的知识点,能够把 Spring Boot...

    田维常
  • Springboot实战

    主要介绍 Spring Boot 在项目中最常使用的功能点,旨在带领学习者快速掌握 Spring Boot 在开发时需要的知识点,能够把 Spring Boot...

    田维常
  • 《一本小小的MyBatis源码分析书》.pdf

    因为其简单易用、便于性能优化的特点,MyBatis在国内的互联网公司占据了绝对的领导地位。

    田维常
  • 搭建简单的Dubbo生产者与消费者

    Dubbo是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。

    Melody132
  • DevOps 从理论到实践指南

    如今 DevOps 已经成为一个流行词,很多公司都在说自己在做 DevOps,但是每个人、每家公司理解的 DevOps 又不尽相同,从 DevOps 诞生的第一...

    笑看
  • 中概股最牛财报!直播这么火为何却只有陌陌赚了大钱?

    今天,陌陌发布了三季度财报,这应该是陌陌,也是所有中概股有史以来最漂亮的财报:净营收达1.57亿美元,同比增长319%。归属于陌陌的净利润为4950万美元,同比...

    罗超频道
  • Springboot实战--助你工作更顺心

    主要介绍 Spring Boot 在项目中最常使用的功能点,旨在带领学习者快速掌握 Spring Boot 在开发时需要的知识点,能够把 Spring Boot...

    田维常
  • Springboot实战

    主要介绍 Spring Boot 在项目中最常使用的功能点,旨在带领学习者快速掌握 Spring Boot 在开发时需要的知识点,能够把 Spring Boot...

    田维常
  • 【一周简报】美团大众点评合并细节曝光:设联席CEO,独立运营

    image.png 智选SDK一周资讯大事记,将会为您呈现过去一周最受欢迎的SDK资讯、投融资、企业活动、人物访谈和创业故事等信息,让您在最短的时间内了解最火爆...

    BestSDK
  • 【连载】两百行Rust代码解析绿色线程原理(四)一个绿色线程的实现

    在我们开始之前,我得提醒你我们编写的代码非常不安全,并且这也不是编写 Rust 代码的 “最佳实践”。我希望在不引入很多不必要的复杂性的前提下使其尽可能安全,所...

    MikeLoveRust

扫码关注云+社区

领取腾讯云代金券