Dubbo同时支持多种协议(以dubbo和rest为例)

一. 背景知识

有时候微服务需要提供给多个消费者, 而不通过的消费者可能希望依据自身情况使用不同的协议. 另一方面, 有时候如果原本服务以 dubbo 协议提供服务, 但是为了调试或者监控方便, 我们也提供 rest 协议.

本文示例服务者同时提供 dubbo 和 rest 协议. 使用的 dubbo 版本为 2.7.1, springboot 版本为 2.1.5.

为了真实地模拟不同微服务之间的调用, 本文将服务者和消费分开. 对应的项目有两个, 分别为dubboshop-inventory(服务者)和dubboshop-order(消费者). 其结构如下:

dubboshop-inventory (库存微服务. 这个项目主要演示服务提供者角色)
 |- dubbo-api: 包含服务接口和 DTO 对象. 打包成 `dubboshop-inventory:1.0.0-snapshot.jar`, 通过 `mvn install`到本地或者`mvn deploy`部署到私服, 在下面`dubboshop-order`项目中引用依赖.
     |- fun.faceless.dubboshop.comms.entity.Result.java
     |- fun.faceless.dubboshop.comms.entity.CommRetCode.java
 |- dubbo-provider: 服务接口具体实现类
     |- fun.faceless.dubboshop.inventory.dubboprovider.DubboApplication.java
     |- fun.faceless.dubboshop.inventory.dubboprovider.impl.InventoryProviderImpl.java
 
dubboshop-order (订单微服务)
 |- dubbo-provider: 订单服务的提供者, 同时是dubboshop-inventory服务的消费者. 这里主要演示其作为消费者的角色.
     |- fun.faceless.dubboshop.order.dubboprovider.impl.OrderProviderImpl.java

二. 通用dubbo配置

本文两个项目都作为服务者, 也都支持dubbo和rest协议, 所以两者dubbo相关的依赖都包含以下几部分.

1) 首先引入通用 dubbo 依赖

<!-- Dubbo dependencies -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-bom</artifactId>
    <type>pom</type>
</dependency>
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo</artifactId>
    <version>${dubbo.version}</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
</dependency>


<!-- dubbo registry: zookeeper dependencies-->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-dependencies-zookeeper</artifactId>
    <version>2.7.1</version>
    <type>pom</type>
    <exclusions>
        <exclusion>
            <artifactId>log4j</artifactId>
            <groupId>log4j</groupId>
        </exclusion>
        <exclusion>
            <artifactId>slf4j-log4j12</artifactId>
            <groupId>org.slf4j</groupId>
        </exclusion>
    </exclusions>
</dependency>

2) dubbo rest 依赖

<!-- for dubbo rest protocol -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-rpc-rest</artifactId>
</dependency>
<!-- for dubbo rest protocol with tomcat server -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
</dependency>

三. 服务者(Provider)实现

3.1 服务接口定义 dubbo-api

1) 数据传输对象定义 Result.java:

注意一定要定义默认构造函数和实现Serializable接口.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result implements Serializable {

    private static final long serialVersionUID = 1L;

    public static String SUCCESS_MSG = "SUCC";
    public static String DEFAULT_FAIL_MSG = "FAIL";

    private String code;
    private String msg;
    private String subCode;
    private String subMsg;
    private String sign;

    private Object data;

    private Result(String code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;

        this.subCode = "";
        this.subMsg = "";
        this.sign = "";
    }

    /**
     * Return succ result with given data.
     * @return
     */
    public static Result succ() {
        return new Result(CommRetCode.OK, SUCCESS_MSG, null);
    }

    /**
     * Return succ result with given data.
     * @param msg
     * @return
     */
    public static Result succ(String msg) {
        return new Result(CommRetCode.OK, msg, null);
    }
    
    /**
     * Return failed result with given code, msg, and data
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public static Result fail(String code, String msg, Object data) {
        return new Result(code, msg, data);
    }
    // 其他省略...
}

2) 通用返回值 CommRetCode.java

package fun.faceless.dubboshop.comms.entity;

public interface CommRetCode {
    /** 一切 ok */
    public final static String OK = "00000";
    // 其他省略...
}

3) 定义服务提供者接口API: InventoryProvider.java

注意 REST 相关的注解都放在接口类中.

package fun.faceless.dubboshop.inventory.dubboprovider;

import javax.ws.rs.*;

import fun.faceless.dubboshop.comms.entity.Result;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.protocol.rest.support.ContentType;

/**
 * Order Dubbo Service
 */
@Service
@Path("inventory")
@Produces({ContentType.APPLICATION_JSON_UTF_8})
@Consumes({ContentType.APPLICATION_JSON_UTF_8})
public interface InventoryProvider {

    @GET
    @Path("hello")
    Result hello();

    /**
     * 减扣商品库存
     */
    @POST
    @Path("debit")
    Result debit(@QueryParam("goodsId") int goodsId, @QueryParam("amount") int amount);
}

3.2 服务实现具体实现

本节示例 Inventory 微服务即库存服务提供者.

1) 提供的服务的具体实现类 InventoryProviderImpl.java

package fun.faceless.dubboshop.inventory.dubboprovider.impl;

import fun.faceless.dubboshop.comms.entity.Result;
import fun.faceless.dubboshop.inventory.dao.InventoryDao;
import fun.faceless.dubboshop.inventory.dubboprovider.InventoryProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
@Service
public class InventoryProviderImpl implements InventoryProvider {

    @Autowired
    InventoryDao inventoryDao;

    @Override
    public Result hello() {
        return Result.succ("hello from inventory center");
    }

    @Override
    public Result debit(int goodsId, int amount) {
        log.debug("debit() goodsId: {}", goodsId);
        log.debug("debit() amount: {}", amount);
        inventoryDao.debit(goodsId, amount);
        return Result.succ();
    }
}

2) 服务启动类 DubboApplication.java

package fun.faceless.dubboshop.inventory.dubboprovider;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableDubbo
@ComponentScan("fun.faceless.dubboshop.inventory")
@MapperScan("fun.faceless.dubboshop.inventory.dao.mapper")
public class DubboApplication {

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

3) 模块配置文件 application-dev.yaml.

多协议支持的配置主要包含:

dubbo.config.multiple = true
dubbo.protocols
# 此处省略项目其他配置...

# ========= Dubbo Provider ==============
dubbo:
  config:
    # 开启多个protocol配置绑定
    multiple: true
  # 注册中心配置
  registry:
    id: dubboshop-registry
    address: zookeeper://yyadmin:2181
    group: dubboshop
    simplified: true
  application:
    name: dubboshop-inventory
    id: dubboshop-inventory
    logger: slf4j
    qos-enable:  false
    qos-accept-foreign-ip: true
    qos-port: 22223
  protocols:
    dubbo:
      name: dubbo
      port: 20882
      server: netty4
    rest:
      name: rest
      server: tomcat
      port: 8082
  scan:
    # dubbo 服务提供者实现类所在包
    base-packages: fun.faceless.dubboshop.inventory.dubboprovider

四. 消费者(Consumer)实现

本节示例 Order 微服务即作为订单的模块的服务者, 同时作为上面库存(Inventory)的消费者. 本例注重消费者.

Dubbo同时支持多种协议(以dubbo和rest为例)

1) 在pom.xml中添加服务者api的依赖:

<!-- inter-project dependencies -->
<dependency>
    <groupId>fun.faceless.dubboshop.inventory</groupId>
    <artifactId>dubboapi</artifactId>
</dependency>

2) 在 OderProviderImpl.java 中消费接口.

package fun.faceless.dubboshop.order.dubboprovider.impl;

public class OrderProviderImpl implements OrderProvider {

    @Autowired
    private OrderDao orderDao;

    // 通过 protocol="dubbo" 或者 protocol="rest" 指定使用的协议
    @Reference(protocol="dubbo")
    private InventoryProvider inventoryProvider;

    @Override
    public int createOrder(int userId, int goodsId, int orderCount) {
        // 调用服务接口
        Result debitResult = inventoryProvider.debit(goodsId, orderCount);
        
        return this.saveOrder(userId, goodsId, orderCount);
    }

    // 省略其他代码...
}

五. 注意事项

5.1 返回值对象一定要有默认构造函数并实现 Serializiable 接口.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result implements Serializable {

    private static final long serialVersionUID = 1L;
    
    // ...

如果没有默认构造函数, 则在使用 rest protocol 时, 返回值无法消费端反序列化. 消费端会报类似如下异常:

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class fun.faceless.xxx.Result]: can not instantiate from JSON object (need to add/enable type information?)

如果没有实现 Serializiable 接口, 则在使用 dubbo protocol 时, 服务提供者无法正常序列化返回值. 服务 (provider) 端会报类似如下异常:

Caused by: org.apache.dubbo.remoting.RemotingException: Failed to send response: Response [id=2, version=2.0.2, status=20, event=false, error=null, result=RpcResult [result=Result(code=00000, msg=SUCC, subCode=, subMsg=, sign=, data=null), exception=null]], cause: java.lang.IllegalStateException: Serialized class fun.faceless.dubboshop.comms.entity.Result must implement java.io.Serializable
java.lang.IllegalStateException: Serialized class fun.faceless.dubboshop.comms.entity.Result must implement java.io.Serializable

5.2 调试时修改依赖模块的代码, 注意及时install/deploy

如果修改公共项目, 或者服务提供者接口所在的module, 在 mvn installmvn deploy 之后, 一定也要记得再调用这些 module 的项目重新导入依赖, 否则会因为缓存, 即便重启消费者服务, 也无济于事.

5.3 REST 注解放到服务接口上

对于 rest protocol, 如果是将接口单独打包 (即不带实现类在包内) 提供给消费者. 那么需要将 JAX-RS 相关的注解放到接口上. 否则会报如下错误:

RESTEASY004600: You must use at least one, but no more than one http method annotation on XXX

这是因为 resteasy jax-rs 2客户端似乎不直接接受实现类。要使其工作,必须创建一个正确注释的接口。示例接口注解:

// InventoryProvider.java, 在 `dubboshop-inventory`项目`dubbo-api`模块中, 单独发布给消费者使用.

@Service
@Path("inventory")
@Produces({ContentType.APPLICATION_JSON_UTF_8})
@Consumes({ContentType.APPLICATION_JSON_UTF_8})
public interface InventoryProvider {

    @GET
    @Path("hello")
    Result hello();

    /**
     * 减扣商品库存
     */
    @POST
    @Path("debit")
    Result debit(@QueryParam("goodsId") int goodsId, @QueryParam("amount") int amount);
}

对应的实现类如下:

// InventoryProviderImpl.java, 在 `dubboshop-inventory`项目`dubbo-provider`模块中, 与消费者无关.

@Slf4j
@Service
public class InventoryProviderImpl implements InventoryProvider {

    @Autowired
    InventoryDao inventoryDao;

    @Override
    public Result hello() {
        return Result.succ("hello from inventory center");
    }

    @Override
    public Result debit(int goodsId, int amount) {
        inventoryDao.debit(goodsId, amount);
        return Result.succ();
    }
}

5.4 消费端可以指定服务的服务方式

@Reference(protocol="dubbo")
// 或 @Reference(protocol="rest")
private InventoryProvider inventoryProvider;


很遗憾的说,推酷将在这个月底关闭。人生海海,几度秋凉,感谢那些有你的时光。

原文 

https://segmentfault.com/a/1190000023355175

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » Dubbo同时支持多种协议(以dubbo和rest为例)

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址