【肥朝】如何手寫實現簡易的Dubbo?

前言

結束了集羣容錯服務發佈原理這兩個小專題以後,有朋友問我服務引用何時開始,本篇爲服務引用的啓蒙篇.以前是一直和你們一塊兒看源碼,鑑於Talk is cheap.Show me your code,因此本篇將和你們一塊兒寫寫代碼.php

插播面試題

  • dubbo的原理是怎麼樣的?請簡單談談java

  • 有沒有考慮過本身實現一個相似dubbo的RPC框架,若是有,請問你會若是着手實現?(面試高頻題,區分度高)面試

  • 你說你用過mybatis,那你知道Mapper接口的原理嗎?(若是回答得不錯,而且提到動態代理這個關鍵詞會繼續往下問,那這個動態代理又是如何經過依賴注入到Mapper接口的呢?)spring

直入主題

簡單原理

談到dubbo的原理,咱們就必須首先要知道,dubbo的基本概念,通俗的說,就是dubbo是幹嗎的設計模式

dubbo是一個分佈式服務框架,致力於提供高性能和透明化的RPC遠程服務調用方案,以及SOA服務治理方案服務器

在此以前,就必需要講講如下幾個簡單又容易混淆的概念網絡

  • 集羣

同一個業務,部署在多個服務器上mybatis

  • 分佈式

一個業務分拆多個子業務,部署在不一樣的服務器上架構

  • RPC

RPC(Remote Procedure Call Protocol)---遠程過程調用app

咱們捕捉到幾個重要的關鍵詞,分佈式,透明化,RPC.

既然各服務是部署在不一樣的服務器上,那服務間的調用就是要經過網絡通訊,簡單的用圖描述以下:

以前在[dubbo源碼解析-本地暴露]的時候就有不少朋友留言問到,這個本地暴露有什麼用.首先,dubbo做爲一個被普遍運用的框架,點滴的性能提高,那麼受益者都是很大一個數量.這也就是爲何JDK的源碼,都喜歡用位運算.好比圖中的UserServiceRoleService服務是在同一模塊內的,他們直接的通訊經過JVM性能確定要比經過網絡通訊要好得多.這就是爲何dubbo在設計上,既有遠程暴露,又有本地暴露的緣由.

既然涉及到了網絡通訊,那麼服務消費者調用服務以前,都要寫各類網絡請求,編解碼之類的相關代碼,明顯是很不友好的.dubbo所說的透明,就是指,讓調用者對網絡請求,編解碼之類的細節透明,讓咱們像調用本地服務同樣調用遠程服務,甚至感受不到本身在調用遠程服務.

說了這麼多,那到底怎麼作?要實現這個需求,咱們很容易想到一個關鍵詞,那就是動態代理

public interface MenuService {
    void sayHello();
}
複製代碼
public class MenuServiceImpl implements MenuService{
    @Override
    public void sayHello() {
    }
}
複製代碼
public class ProxyFactory implements InvocationHandler {
    private Class interfaceClass;
    public ProxyFactory(Class interfaceClass) {
        this.interfaceClass = interfaceClass;
    }
    //返回代理對象,此處用泛型爲了調用時不用強轉,用Object須要強轉
    public <T> T getProxyObject(){
        return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),//類加載器
                new Class[]{interfaceClass},//爲哪些接口作代理(攔截哪些方法)
                this);//(把這些方法攔截到哪處理)
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method);
        System.out.println("進行編碼");
        System.out.println("發送網絡請求");
        System.out.println("將網絡請求結果進行解碼並返回");
        return null;
    }
}
複製代碼
public void test() throws Exception {
    ProxyFactory proxyFactor = new ProxyFactory(MenuService.class);
    MenuService menuService = proxyFactor.getProxyObject();
    menuService.sayHello();
    //輸出結果以下:
    //public abstract void com.toby.rpc.MenuService.sayHello()
    //進行編碼
    //發送網絡請求
    //將網絡請求結果進行解碼並返回
}
複製代碼

看到這裏可能有朋友要吐槽了,我都看了你幾個月的源碼解析了,上面說的那些我早就懂了,那我還關注肥朝公衆號幹嗎.我要的是整出一個相似dubbo的框架,性能上差點不要緊,至少外觀使用上要差很少,好比咱們平時使用dubbo都是先在配置文件配置這麼個東西

<dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService"/>
複製代碼

而後用在用@Autowired依賴注入來使用的,說白了,逼格要有!

與spring融合

咱們假如要寫一個簡單的RPC,就取名叫tobyRPC(肥朝英文名爲toby),其實我我的是比較喜歡截圖,可是部分朋友和我反覆強調貼代碼,那這裏我就貼代碼吧

1.設計配置屬性和JavaBean

public class ReferenceBean<T> extends ReferenceConfig<T> implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return get();
    }
    @Override
    public Class<?> getObjectType() {
        return getInterfaceClass();
    }
    @Override
    public boolean isSingleton() {
        return true;
    }
}
複製代碼
public class ReferenceConfig<T> {
    private Class<?> interfaceClass;
    // 接口代理類引用
    private transient volatile T ref;
    public synchronized T get() {
        if (ref == null) {
            init();
        }
        return ref;
    }
    private void init() {
        ref = new ProxyFactory(interfaceClass).getProxyObject();
    }
    public Class<?> getInterfaceClass() {
        return interfaceClass;
    }
    public void setInterfaceClass(Class<?> interfaceClass) {
        this.interfaceClass = interfaceClass;
    }
}
複製代碼

2.編寫XSD文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns="http://toby.com/schema/tobyRPC" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:tool="http://www.springframework.org/schema/tool" targetNamespace="http://toby.com/schema/tobyRPC">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
    <xsd:import namespace="http://www.springframework.org/schema/beans"/>
    <xsd:import namespace="http://www.springframework.org/schema/tool"/>

    <xsd:complexType name="referenceType">
        <xsd:complexContent>
            <xsd:extension base="beans:identifiedType">
                <xsd:attribute name="interface" type="xsd:token" use="required">
                    <xsd:annotation>
                        <xsd:documentation><![CDATA[ The service interface class name. ]]></xsd:documentation>
                        <xsd:appinfo>
                            <tool:annotation>
                                <tool:expected-type type="java.lang.Class"/>
                            </tool:annotation>
                        </xsd:appinfo>
                    </xsd:annotation>
                </xsd:attribute>
            </xsd:extension>
        </xsd:complexContent>
    </xsd:complexType>

    <xsd:element name="reference" type="referenceType">
        <xsd:annotation>
            <xsd:documentation><![CDATA[ Reference service config ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:element>

</xsd:schema>
複製代碼

3.編寫NamespaceHandlerBeanDefinitionParser完成解析工做

public class TobyRPCBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
    protected Class getBeanClass(Element element) {
        return ReferenceBean.class;
    }
    protected void doParse(Element element, BeanDefinitionBuilder bean) {
        String interfaceClass = element.getAttribute("interface");
        if (StringUtils.hasText(interfaceClass)) {
            bean.addPropertyValue("interfaceClass", interfaceClass);
        }
    }
}
複製代碼
public class TobyRPCNamespaceHandler extends NamespaceHandlerSupport {
    public void init() {
        registerBeanDefinitionParser("reference", new TobyRPCBeanDefinitionParser());
    }
}
複製代碼

4.編寫spring.handlersspring.schemas串聯起全部部件

spring.handlers

http\://toby.com/schema/tobyRPC=com.toby.config.TobyRPCNamespaceHandler
複製代碼

spring.schemas

http\://toby.com/schema/tobyRPC.xsd=META-INF/tobyRPC.xsd
複製代碼

5.建立配置文件

<?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:tobyRPC="http://toby.com/schema/tobyRPC" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://toby.com/schema/tobyRPC http://toby.com/schema/tobyRPC.xsd">
	
	<tobyRPC:reference id="menuService" interface="com.toby.rpc.MenuService" />
	
</beans>
複製代碼

demo結構截圖以下:

萬事俱備,那咱們跑個單元測試看看

運行結果如咱們所料.可是具體要怎麼編碼,怎麼發送請求,又如何解碼好像也沒說啊.沒說?沒說就對了.在完結服務引用這個小專題後,還會重點和你們看一下dubbo中的編解碼,spi,javassist等重點內容源碼,等粗略把整個框架的思想都掌握後,再手把手臨摹一個五臟俱全(包含設計模式,dubbo架構設計)的簡易dubbo框架.總之一句話,關注肥朝公衆號便可.

敲黑板劃重點

爲何面試都喜歡問原理,難道都是爲了裝逼?固然不是,明白了原理,不少東西都是一通百通的.咱們來看mybatis的這道面試題.首先Mapper接口的原理,能夠參考我以前的圖解源碼 | MyBatis的Mapper原理 ,其實說白了,就是給Mapper接口注入一個代理對象,而後動態代理對象調用方法會被攔截到invoke中,而後在這個invoke方法中,作了一些不可描述的事情(老司機能夠盡情YY).而這一切的前提,都是要無聲無息的把動態代理對象注入進去.其實注入進去的原理和dubbo也是同樣的,咱們簡單看兩個圖

寫在最後

相關文章
相關標籤/搜索