Dubbox(二):簡単な入門

63158 ワード

原文:http://www.jianshu.com/p/c602b347de88
0.準備
  • インストール登録センター:Zookeeper、Dubboxが持参したdubbo-registry-simple;
  • DubboKeeperモニタを取り付ける:https://github.com/dubboclub/dubbokeeper;

  • 以上の2点の準備は、本文の重点ではなく、詳しく紹介しないで、インストールは比較的簡単で、自分で関連資料を調べて勉強します.
    1.サービス側
    1.2インタフェース定義
  • Mavenモジュールの作成:msa-demo-api

    msa-demo-api
  • msa-demo-api:pomを構成する.xml
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>dubboartifactId>
      <version>2.8.4version>
    dependency>
    
    
    
    <dependency>
       <groupId>org.projectlombokgroupId>
       <artifactId>lombokartifactId>
    dependency>
    
    
    
    <dependency>
      <groupId>org.jboss.resteasygroupId>
      <artifactId>resteasy-jaxrsartifactId>
      <version>3.0.7.Finalversion>
    dependency>
    <dependency>
      <groupId>org.jboss.resteasygroupId>
      <artifactId>resteasy-clientartifactId>
      <version>3.0.7.Finalversion>
    dependency>
    <dependency>
      <groupId>javax.validationgroupId>
      <artifactId>validation-apiartifactId>
      <version>1.0.0.GAversion>
    dependency>
    
    
    
    <dependency>
      <groupId>org.jboss.resteasygroupId>
      <artifactId>resteasy-jackson-providerartifactId>
      <version>3.0.7.Finalversion>
    dependency>
    
    
    
    <dependency>
      <groupId>org.jboss.resteasygroupId>
      <artifactId>resteasy-jaxb-providerartifactId>
      <version>3.0.7.Finalversion>
    dependency>
    
    
    
    <dependency>
      <groupId>org.jboss.resteasygroupId>
      <artifactId>resteasy-nettyartifactId>
      <version>3.0.7.Finalversion>
    dependency>
    
    
    
    <dependency>
      <groupId>org.jboss.resteasygroupId>
      <artifactId>resteasy-jdk-httpartifactId>
      <version>3.0.7.Finalversion>
    dependency>
    
    
    
    <dependency>
      <groupId>org.apache.tomcat.embedgroupId>
      <artifactId>tomcat-embed-coreartifactId>
      <version>8.0.11version>
    dependency>
    <dependency>
      <groupId>org.apache.tomcat.embedgroupId>
      <artifactId>tomcat-embed-logging-juliartifactId>
      <version>8.0.11version>
    dependency>
    
    
    
    <dependency>
      <groupId>com.esotericsoftware.kryogroupId>
      <artifactId>kryoartifactId>
      <version>2.24.0version>
    dependency>
    <dependency>
      <groupId>de.javakaffeegroupId>
      <artifactId>kryo-serializersartifactId>
      <version>0.26version>
    dependency>
    
    
    
    <dependency>
      <groupId>de.ruedigermoellergroupId>
      <artifactId>fstartifactId>
      <version>1.55version>
    dependency>
    
    
    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>2.3.3version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.3.3version>
    dependency>
    
    以上のPOMはdubbox-2.8から配置する.4から、すべての依存ライブラリの使用方法はdubboの従来のものと同じになります.すなわち、REST、Kyro、FST、Jacksonなどの機能を使用するには、ユーザーが自分で関連する依存を手動で追加する必要があります.
  • 定義インタフェース:UserServices.java
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    public interface UserService {
       User getUser(Long id);
       Long registerUser(User user);
    }
  • 定義RESTインタフェース:AnotherUserRestServices.java
    package com.alibaba.dubbo.demo.user.facade;
    import com.alibaba.dubbo.demo.user.User;
    import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
    import javax.validation.constraints.Min;
    import javax.ws.rs.*;
    import javax.ws.rs.core.MediaType;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    //  Dubbo   REST        JAX-RS annotation      ,
    //        ,     annotation         。   , 
    //        annotation        ,           .
    //
    //       ,     annotation       ,  annotation 
    // java         ,        。       ,      
    //          ,              。
    //   ,     ,      dubbo              , annotation       。
    //               annotation,     annotation     ,    annotation     。
    @Path("u")
    @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
    @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
    public interface AnotherUserRestService {
    
       @GET
       @Path("{id : \\d+}")
       //    REST                 ,  JAX-RS  ,
       //      HTTP  MIME header(content-type accept)                。
       // @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
       //    dubbo ,                  ,    URL  (.json .xml)   
       //        。  ,     annotation ,    http://localhost:8888/users/1001.json
       //     json  ,    http://localhost:8888/users/1002.xml    xml  ,
       //   HTTP Header     。Twitter、    REST API        。
       //       HTTP header,     , dubbo REST        annotation               。
       //   :     XML    , annotation     MediaType.TEXT_XML,    MediaType.APPLICATION_XML,
       //   TEXT_XML     ,          URL           ,     TEXT_XML    。
       User getUser(@PathParam("id") @Min(1L) Long id);
    
       @POST
       @Path("register")
       RegistrationResult registerUser(User user);
    }
  • 定義エンティティ:User.java
    package com.alibaba.dubbo.demo.user;
    import lombok.Data;
    import org.codehaus.jackson.annotate.JsonProperty;
    import javax.validation.constraints.Min;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import java.io.Serializable;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    //   JAX-RS          JAXB(Java API for XML Binding)         XML    ,
    //             XML             JAXB annotation(@XmlRootElement) ,        。
    @Data
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class User implements Serializable {
    
       @NotNull
       @Min(1L)
       private Long id;
    
       // REST       service    JSON/XML            /    。
       //       ,               ,       。
       // Dubbo  REST    JAXB XML   , Jackson JSON   ,
       //         JAXB Jackson annotation       。
       @JsonProperty("username")
       @XmlElement(name = "username")
       @NotNull
       @Size(min = 6, max = 50)
       private String name;
    }
  • REST応答結果エンティティ:RegistrationResult.java
    package com.alibaba.dubbo.demo.user.facade;
    import lombok.Data;
    import javax.xml.bind.annotation.XmlRootElement;
    import java.io.Serializable;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    //   ,  service        Java  primitive  ( int,long,float,double ),
    //          wrapper  ,  JAXB       primitive  。        XML      ,
    //             XML JSON   。
    //   wrapper        Data Transfer Object(DTO)  ,  DTO               。
    @Data
    @XmlRootElement
    public class RegistrationResult implements Serializable {
       private Long id;
    }

  • 1.3サービス実装
  • Mavenモジュールの作成:msa-demo-provider

    msa-demo-provider
  • msa-demo-provider:pomを構成する.xml
    
    <dependency>
       <groupId>com.alibabagroupId>
       <artifactId>msa-demo-apiartifactId>
       <version>1.0-SNAPSHOTversion>
    dependency>
    
  • UserServiceインタフェースを実現する:UserServiceImpl.java
    package com.alibaba.dubbo.demo.user;
    import lombok.extern.slf4j.Slf4j;
    import java.util.concurrent.atomic.AtomicLong;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    @Slf4j
    public class UserServiceImpl implements UserService {
       private final AtomicLong idGen = new AtomicLong();
       public User getUser(Long id) {
           User user = new User();
           user.setId(id);
           user.setName("username" + id);
           return user;
       }
    
       public Long registerUser(User user) {
           // System.out.println("Username is " + user.getName());
           return idGen.incrementAndGet();
       }
    }
  • RESTインタフェースAnotherUserRestServices:AnotherUserRestServiceImplを実現する.java
    package com.alibaba.dubbo.demo.user.facade;
    import com.alibaba.dubbo.demo.user.User;
    import com.alibaba.dubbo.demo.user.UserService;
    import com.alibaba.dubbo.rpc.RpcContext;
    import lombok.extern.slf4j.Slf4j;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    @Slf4j
    public class AnotherUserRestServiceImpl implements AnotherUserRestService {
    
       private UserService userService;
    
       public void setUserService(UserService userService) {
           this.userService = userService;
       }
    
       public User getUser(Long id) {
           System.out.println("Client name is " + RpcContext.getContext().getAttachment("clientName"));
           System.out.println("Client impl is " + RpcContext.getContext().getAttachment("clientImpl"));
           return userService.getUser(id);
       }
    
       public RegistrationResult registerUser(User user) {
           Long id = userService.registerUser(user);
           RegistrationResult registrationResult = new RegistrationResult();
           registrationResult.setId(id);
           return registrationResult;
       }
    }
  • DubboxとSpringの統合構成:msa-demo-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-2.5.xsd
         http://code.alibabatech.com/schema/dubbo
         http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    
      
      <dubbo:application name="msa-demo-provider" owner="tbr" organization="tbr"/>
      <dubbo:monitor address="x.x.x.x:20884"/>
    
      
      <dubbo:registry protocol="zookeeper" address="x.x.x.x:2181,x.x.x.x:2181,x.x.x.x:2181"/>
      <dubbo:protocol name="dubbo" port="20880" serialization="kryo"/>
    
      
    
      
    
      
      <dubbo:protocol name="rest" port="8888" threads="500" contextpath="services" server="tomcat" accepts="500"
                     extension="com.alibaba.dubbo.demo.extension.TraceInterceptor,
                     com.alibaba.dubbo.demo.extension.TraceFilter,
                     com.alibaba.dubbo.demo.extension.ClientTraceFilter,
                     com.alibaba.dubbo.demo.extension.DynamicTraceBinding,
                     com.alibaba.dubbo.demo.extension.CustomExceptionMapper,
                     com.alibaba.dubbo.rpc.protocol.rest.support.LoggingFilter"/>
    
      
    
      <dubbo:protocol name="http" port="8889"/>
      <dubbo:protocol name="hessian" port="8890"/>
      <dubbo:protocol name="webservice" port="8892"/>
    
      
      <dubbo:service interface="com.alibaba.dubbo.demo.user.UserService" ref="userService" protocol="dubbo" group="xmlConfig"/>
    
      
      <dubbo:service interface="com.alibaba.dubbo.demo.user.facade.AnotherUserRestService" ref="anotherUserRestService" protocol="rest" timeout="2000" connections="100" validation="true"/>
    
      <bean id="userService" class="com.alibaba.dubbo.demo.user.UserServiceImpl"/>
    
      <bean id="anotherUserRestService" class="com.alibaba.dubbo.demo.user.facade.AnotherUserRestServiceImpl">
          <property name="userService" ref="userService"/>
      bean>
    
      
    beans>
  • はdubboを配置する.properties
    #dubbo.container=log4j,spring
    #dubbo.application.name=demo-provider
    #dubbo.application.owner=
    #dubbo.registry.address=multicast://224.5.6.7:1234
    #dubbo.registry.address=zookeeper://127.0.0.1:2181
    #dubbo.registry.address=redis://127.0.0.1:6379
    #dubbo.registry.address=dubbo://127.0.0.1:9090
    #dubbo.monitor.protocol=registry
    #dubbo.protocol.name=dubbo
    #dubbo.protocol.port=20880
    #dubbo.service.loadbalance=roundrobin
    #dubbo.log4j.file=logs/msa-demo-provider.log
    #dubbo.log4j.level=INFO
    #dubbo.log4j.subdirectory=20880
    dubbo.application.logger=slf4j
    dubbo.spring.config=classpath*:msa-*.xml

  • 1.4サービス起動
    サービス起動クラスを定義します.
    package com.alibaba.dubbo.demo.provider;
    /**
      * @author TaoBangren
      * @version 1.0
      * @since 2017/5/17   9:26
      */
    public class DemoProvider {
          public static void main(String[] args) {
              com.alibaba.dubbo.container.Main.main(args);
          }
    }

    mainメソッドの起動を実行し、次のログ出力が表示された場合、msa-demo-providerの起動に成功しました.

    msa-demo-provider起動成功
    DubboKeeperモニタの大皿を見て、msa-demo-providerリリースサービスは成功して、私たちがリリースした2つのインタフェースを見ることができます:

    msa-demo-providerリリースサービス成功
    2.クライアント
  • Mavenモジュールの作成:msa-demo-client

    msa-demo-client
  • msa-demo-client:pomを構成する.xml
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>msa-demo-apiartifactId>
      <version>1.0-SNAPSHOTversion>
    dependency>
    
  • DubboxとSpringの統合構成:msa-demo-client.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-2.5.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    
       
       
    
       
       
       
    
       <dubbo:reference id="userService" interface="com.alibaba.dubbo.demo.user.UserService" group="xmlConfig"/>
       <dubbo:reference id="anotherUserRestService" interface="com.alibaba.dubbo.demo.user.facade.AnotherUserRestService"/>
    
       
    beans>

  • 3.消費者側
    3.1消費側実現
  • Mavenモジュールの作成:msa-demo-consumer

    msa-demo-consumer
  • msa-demo-consumer:pomを構成する.xml
    
    <dependency>
       <groupId>com.jeasygroupId>
       <artifactId>msa-demo-clientartifactId>
       <version>1.0-SNAPSHOTversion>
    dependency>
    
  • 消費者側テストクラスを作成する:DemoAction.java
    package com.alibaba.dubbo.demo;
    import com.alibaba.dubbo.rpc.RpcContext;
    import com.alibaba.dubbo.demo.user.User;
    import com.alibaba.dubbo.demo.user.UserService;
    import com.alibaba.dubbo.demo.user.facade.AnotherUserRestService;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    public class DemoAction {
    
       private UserService userService;
    
       private AnotherUserRestService anotherUserRestService;
    
       public void setUserService(final UserService userService) {
           this.userService = userService;
       }
    
       public void setAnotherUserRestService(final AnotherUserRestService anotherUserRestService) {
           this.anotherUserRestService = anotherUserRestService;
       }
    
       public void start() throws Exception {
           User user = new User();
           user.setId(1L);
           user.setName("larrypage");
    
           System.out.println("SUCCESS: registered user with id by rest" + anotherUserRestService.registerUser(user).getId());
           System.out.println("SUCCESS: registered user with id " + userService.registerUser(user));
    
           RpcContext.getContext().setAttachment("clientName", "demo");
           RpcContext.getContext().setAttachment("clientImpl", "dubbox rest");
           System.out.println("SUCCESS: got user by rest" + anotherUserRestService.getUser(1L));
           System.out.println("SUCCESS: got user " + userService.getUser(1L));
       }
    }
  • DubboxとSpringの統合構成:msa-demo-consumer.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-2.5.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    
       
       <dubbo:application name="msa-demo-consumer" owner="tbr" organization="tbr"/>
    
       
       <dubbo:registry protocol="zookeeper" address="x.x.x.x:2181,x.x.x.x:2181,x.x.x.x:2181"/>
       <dubbo:monitor address="x.x.x.x:20884"/>
    
       <bean class="com.alibaba.dubbo.demo.DemoAction" init-method="start">
           <property name="userService" ref="userService"/>
           <property name="anotherUserRestService" ref="anotherUserRestService"/>
       bean>
    beans>
  • はdubboを配置する.properties
    #dubbo.container=log4j,spring
    #dubbo.application.name=demo-consumer
    #dubbo.application.owner=
    #dubbo.registry.address=multicast://224.5.6.7:1234
    #dubbo.registry.address=zookeeper://127.0.0.1:2181
    #dubbo.registry.address=redis://127.0.0.1:6379
    #dubbo.registry.address=dubbo://127.0.0.1:9090
    #dubbo.monitor.protocol=registry
    #dubbo.log4j.file=logs/msa-demo-consumer.log
    #dubbo.log4j.level=INFO
    dubbo.application.logger=slf4j
    dubbo.spring.config=classpath*:msa-*.xml

  • 3.2消費者側テスト
    消費開始クラスの定義:
    package com.jeasy;
    /**
     * @author TaoBangren
     * @version 1.0
     * @since 2017/5/17   9:26
     */
    public class DemoConsumer {
          public static void main(String[] args) {
              com.alibaba.dubbo.container.Main.main(args);
          }
    }

    mainメソッドの起動を実行し、次のログ出力が表示された場合、msa-demo-consumerが起動に成功しました.

    msa-demo-consumer起動成功
    サービス側は、サービス呼び出しログ情報を出力し、次のように呼び出しに成功します.

    サービス側呼び出しログ
    4.仕様使用
    モジュール
    説明
    必要かどうか
    msa-xxx-api
    インタフェース&エンティティの定義
    なければならない
    msa-xxx-provider
    apiモジュールに依存し、サービスインタフェースを実現し、サービスを提供する
    なければならない
    msa-xxx-client
    apiモジュール、Springプロファイル&テスト例に依存して、サードパーティ呼び出しサービスに使用できます.
    なければならない
    msa-xxx-consumer
    クライアントモジュールに依存して、クライアントモジュールが直接アプリケーションに結合しないように、モジュールを保持することをお勧めします.
    オプション
    5.おすすめ読書
    5.1 Dubbox関連資源
  • ソースアドレス:https://github.com/dangdangdotcom/dubbox
  • DubboでRESTスタイルのリモートコールを開発:https://dangdangdotcom.github.io/dubbox/rest.html
  • Dubboで効率的なJavaシーケンス化を使用:https://dangdangdotcom.github.io/dubbox/serialization.html
  • JavaConfig方式を使用してdubboxを構成します.https://dangdangdotcom.github.io/dubbox/java-config.html
  • Dubbo Jacksonシーケンス化使用説明:https://dangdangdotcom.github.io/dubbox/jackson.html
  • Demo : https://dangdangdotcom.github.io/dubbox/demo.html
  • 当ネットオープンソースDubbox、拡張DubboサービスフレームワークはRESTスタイルリモートコールをサポートする:http://www.infoq.com/cn/news/2014/10/dubbox-open-source
  • Dubbox Wiki : https://github.com/dangdangdotcom/dubbox/wiki

  • 5.2 Dubbo関連資源
  • ソースアドレス:https://github.com/alibaba/dubbo
  • Dubbo Wiki : https://github.com/alibaba/dubbo/wiki
  • http://dubbo.io/

  • 作者:陶邦仁
    リンク:http://www.jianshu.com/p/c602b347de88
    出典:簡書
    著作権は作者の所有である.商業転載は著者に連絡して許可を得てください.非商業転載は出典を明記してください.