Dubbo 本地存根

作用

在真正调用生产者之前,如果需要进行参数验证等,就可以使用本地存根

实现具体步骤:

1.创建存根类,实现消费者的接口

package com.jym.stub;

import com.jym.bean.UserAddress;
import com.jym.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: jym-service-consumer
 * @description:
 * @author: jym
 * @create: 2020/02/19
 */
public class UserServiceStub implements UserService {

    private UserService userService;

    public UserServiceStub(UserService userService) {
        this.userService = userService;
    }

    /**
     *  传入的是远程代理对象
     */
    public List<UserAddress> getUserAddressList(String s) {
        if (null==s){
            return new ArrayList<UserAddress>();
        }
        return userService.getUserAddressList(s);
    }
}

说明:
dubbo 真正调用生产者的实际是存根类
必须要有构造方法

在xml中配置:使用stub
    <!-- 配置本地存根 -->
    <dubbo:reference interface="com.jym.service.UserService" id="userService2"
                     retries="5" timeout="4000" version="2.0.0" check="false" stub="com.jym.stub.UserServiceStub"/>
消费者业务代码
package com.jym.service.impl;

import com.jym.bean.UserAddress;
import com.jym.service.OrderService;
import com.jym.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @program: jym-service-consumer
 * @description: 1.将服务注册到注册中心(如何来暴露服务)
 *                  导入dubbo依赖(2.6.2)
 *               2.让服务消费者去注册中心,订阅服务提供者的提供地址
 * @author: jym
 * @create: 2020/02/17
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserService userService2;

    public List<UserAddress> initOrder(String userId) {
        // 查询用户收货地址
        List<UserAddress> userAddressList = userService2.getUserAddressList(userId);
        if (userAddressList.size()==0) {
            System.out.println("传入的参数为null");
        }
        for (UserAddress userAddress : userAddressList) {
            System.out.println(userAddress.getConsignee()+":"+userAddress.getUserAddress());
        }
        return userAddressList;
    }

    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("consumer.xml");
        OrderService orderService = classPathXmlApplicationContext.getBean(OrderService.class);
        orderService.initOrder(null);
        System.in.read();
    }

}

当我们传入null的结果:
Dubbo 本地存根_第1张图片

学习年限不足,知识过浅,说的不对请见谅。

世界上有10种人,一种是懂二进制的,一种是不懂二进制的。

你可能感兴趣的:(Dubbo)