Hello everyone , I'm Xiaoyu .

Dubbo Originated from Alibaba , For those of us who do e-commerce development , Basically the technology of choice , So why a mere soa Service governance framework , Will be favored by so many people ?

Today, let's take a look at one of the micro service frameworks with Xiaoyu Dubbo Let's read it in detail .

Preface

The continuous development of the Internet , The scale of web applications continues to grow , Conventional vertical application architectures can no longer cope .

The further development of servitization , More and more services , The invocation and dependency relationships between services are becoming more and more complex , The birth of Service oriented Architecture of (SOA),

Therefore, a series of corresponding technologies have been derived , Such as the provision of services 、 The service call 、 Connection processing 、 Communication protocol 、 Serialization mode 、 Service discovery 、 Service routing 、 Output behavior logs, etc encapsulate Service framework of .

So the distributed system Service governance And the frame came out ,Dubbo That's how it happened .

Concept

Dubbo It's a high performance 、 Lightweight open source RPC frame 、 Provide services to automatically register 、 Automatic discovery and other efficient governance solutions , You can talk to Spring frame Seamless integration .

To put it simply ,dubbo It's a distributed service framework , It can be used when there is a distributed need dubbo Framework , Use dubbo The benefits of :

1、 Transparent remote method calls

2、 Soft load balancing and fault tolerance mechanism

3、 Service automatic registration and discovery

4、 It provides perfect service interface management and monitoring functions

RPC

brief introduction

RPC Its full name is remote procedure call, Remote procedure call . Like two servers A and B,A Deploy an application on the server ,B Deploy an application on the server ,A The application on the server wants to call B The method provided by the application on the server , Because the two applications are not in the same memory space , Can't call directly , So we need to use the Internet to Express the semantics of the call and convey the data of the call .

RPC It's not a specific technology , It's the whole network Call the procedure remotely .

RPC It's a general concept , Strictly speaking, all remote procedure calling means belong to RP C Category . All kinds of development languages have their own RPC frame .Java Medium RPC There are more frames , Widely used are RMI、Hessian、Dubbo etc. .

principle

Service consumer (client) The invocation invokes the service as a local invocation . Client stub (client stub) After receiving the call, responsible for Method 、 Parameters And so on are encoded into a message body that can be transmitted in the network . then , After the client stub finds the service address , Send the message to the server .

service provider (server) Receive the serialized message , Just decode the message . then , Call the local service according to the decoding result , After execution , Will result in Package and send To consumers .

After the service consumer receives the execution result , It's also decode We get the result after the test .

Use scenarios

RPC Distributed services , Split the application for service , Improve development efficiency , Tuning performance , Save competitive resources

Configuration Management , Address information of solution service is increasing dramatically , The problem of difficult configuration

Service dependence , Solve the problem of complex dependency relationship between services

Service expansion , With the increasing number of visits , The problem of dynamically expanding the service provider's machine

Core functions

Remoting: Telematics , Provide for a variety of NIO frame Abstract encapsulation , Include “ Synchronous to asynchronous ” and “ request - Respond to ” Mode of information exchange .

Cluster: Service Framework , Provides interface based methods for Transparent remote procedure call , Including multi protocol support , And soft load balancing , Failure tolerance , Address routing , Dynamic configuration and other cluster support .

Registry: Service registry , Service auto discovery : Based on registry directory service , So that service consumers can Dynamic search service provider , Make the address transparent , Enable service providers to smoothly add or reduce machines .

Core components

Provider: Service provider

Consumer: The service consumer that invokes the remote service

Registry: Service registration and discovery registry

Monitor: Monitoring Center for counting the number and time of service calls

Container: Service run container

Service registration and discovery

The process is as follows :

1、Provider( Provider ) binding Specify the port and start the service

2、 The donor connects to the registry , Concurrent native IP、 port 、 Application information and service delivery information are sent to the registry Storage

3、Consumer( consumer ), Connect to the registry , and send out Application information 、 Please send the service information to the registry

4、 According to the service information requested by consumers, the Registration Center matching The corresponding provider list is sent to Consumer Application cache .

5、Consumer When a remote call is initiated, it is initiated based on the cached consumer list call .

6、Provider Status changes are notified to the registry in real time 、 In real time by the registry push to Consumer The reason for the design :

Consumer And Provider Uncouple , Both sides can Horizontal increase and decrease Number of nodes . The registry itself can be a peer-to-peer cluster , Nodes can be increased or decreased dynamically , And when any one goes down , take Automatic switch Go to the other one

7、 De centralization , The two sides Not just lazy Registry Center , Even if the registry is completely down for a short time, the service calls will not be affected

8、 Service providers No state , After any one goes down , Not affecting use

Service governance

Governance reasons

Dubbo The main reason of service governance is :

1、 Too many services URL Configuration is difficult .

2、 Load balancing distribution nodes overpressure In this case, you also need to deploy clusters .

3、 service Relying on Chaos , The starting sequence is not clear .

4、 Too many services lead to performance metrics The analysis is difficult , Need to monitor .

The main features

Transparent remote call : Call a remote method just like calling a local method ; Simple configuration , There is no API invasion

Load balancing mechanism :Client End LB, It can be replaced in the intranet F5 Wait for hardware load balancer

Fault tolerant retrial mechanism : service Mock data , Retry count 、 Time out mechanism, etc

Automatic registration discovery : The registry queries the service provider based on the interface name Donor's IP Address , And can smoothly add or remove service providers

Performance log monitoring :Monitor The monitoring center that counts the invocation times and invocation times of the service

Service Governance Center : Routing rules , Dynamic configuration , service degradation , Access control , Weight adjustment , Load balancing , Wait for manual configuration

Automatic Governance Center : nothing , such as : Fuse current limiting mechanism 、 Automatic weight adjustment, etc ( So it can be matched with SpringCloud And so on )

Architecture design

The overall architecture

Let's take a look at Dubbo The overall architecture diagram :

Legend :

The light blue background on the left is Service consumer Interface used , On the light green background on the right is service provider Interface used , On the central axis is the interface used by both sides .

The picture is divided into ten layers from bottom to top , Each layer is One way dependency , The black arrow on the right represents the Dependency relationship , Each layer can be split and reused , among ,Service and Config Layer for API, The other layers are SPI.

The green ones in the picture are Extension interface , The small blue pieces are Implementation class , The figure shows only the implementation classes used to associate the layers .

The blue dotted line in the picture is Initialization process , That is, assemble the chain at startup , The solid red line is Method call procedure , That is, the timing chain , The purple triangle arrow is Inherit , You can think of a subclass as the same node as the parent , The text on the line is called method .

Description of each layer

config Configuration layer : External configuration interface , With ServiceConfig, ReferenceConfig Centered , You can initialize the configuration class directly , It can also be done through spring Parse configuration to generate configuration class

proxy Service agent layer : Service interface transparent agent , The client that generated the service Stub And the server side Skeleton, With ServiceProxy Centered , The extension interface is ProxyFactory

registry Registry level : Encapsulate service address registration and discovery , To serve URL Centered , The extension interface is RegistryFactory, Registry, RegistryService

cluster The routing layer : Encapsulate the routing and load balancing of multiple providers , And bridge the registry , With Invoker Centered , The extension interface is Cluster, Directory, Router, LoadBalance

monitor Monitoring layer :RPC Call times and call time monitoring , With Statistics Centered , The extension interface is MonitorFactory, Monitor, MonitorService

protocol Remote call layer : encapsulation RPC call , With Invocation, Result Centered , The extension interface is Protocol, Invoker, Exporter

exchange The information exchange layer : Encapsulate request response patterns , Synchronous to asynchronous , With Request, Response Centered , The extension interface is Exchanger, ExchangeChannel, ExchangeClient, ExchangeServer

transport Network transport layer : abstract mina and netty For a unified interface , With Message Centered , The extension interface is Channel, Transporter, Client, Server, Codec

serialize Data serialization layer : Some reusable tools , The extension interface is Serialization, ObjectInput, ObjectOutput, ThreadPool

The main module

dubbo-common Common logic modules , Include Util Classes and Generic model .

dubbo-remoting Telematics module , amount to Dubbo Agreed Realization , If RPC use RMI The protocol does not need to use this package .

dubbo-rpc Remote call module , Abstract protocols , And dynamic proxy , Contains only One to one call , Don't care about cluster management .

dubbo-cluster The cluster module , Multiple service providers Disguised as a provider , Include : Load balancing 、 Fault tolerance 、 Routing, etc. , The address list of the cluster can be statically configured , It can also be issued by the registration center .

dubbo-registry Registry module , Based on the address issued by the registry The cluster approach , And the abstraction of various registries .

dubbo-monitor Monitoring module , Statistics service call frequency , Call time , Call chain trace Services .

dubbo-config Configuration module , yes Dubbo foreign Of API , User pass Config Use Dubbo , hide Dubbo All the details .

dubbo-container Container module , It's a Standalone The container of , With simple Main load Spring start-up , Because services usually don't need Tomcat/JBoss etc. Web Characteristics of the container , It is not necessary to use Web Container to load service .

Call mode

Asynchronous call

be based on NIO Non blocking implementation of Parallel call , The client does not need to start multithreading to call multiple remote services in parallel , The cost of multithreading is relatively small

Local call

Used Injvm agreement , It's a fake protocol , It doesn't open the port , No remote call is made , Only in JVM It's directly related to , But enforcement Dubbo Of Filter chain .

Define injvm protocol:

<dubbo:protocol name="injvm" /> 

Set default protocol:

<dubbo:provider protocol="injvm" />

Set service protocol:

<dubbo:service protocol="injvm" />

Use injvm first:( Both service exposure and service reference need to be declared injvm=“true”)

<dubbo:consumer injvm="true" .../>
<dubbo:provider injvm="true" .../>
or
<dubbo:reference injvm="true" .../>  <dubbo:service injvm="true" .../>

Fault tolerance mechanism

Calling process

1、Cluster take Directory In the multiple Invoker Pretend to be a Invoker, Transparent to the upper layer , The camouflage process involves Fault tolerant logic

2、Router Responsible from multiple Invoker Press Routing rules Select a subset , For example, separation of reading and writing , Application isolation, etc

3、LoadBalance Responsible from multiple Invoker Select a specific one for this call , The selection process involves Load balancing Algorithm

Fault tolerant strategy

Dubbo There are six fault tolerance strategies proposed by the official website

1、Failover Cluster

Fail auto switch , When there is failure , Try another server again .( Default )

2、Failfast Cluster

Fast failure , Make only one call , Failure reports an immediate error . Usually used for non idempotent write operations , For example, adding records .

3、Failsafe Cluster

Failure safety , When something unusual happens , Direct to ignore . Usually used to write audit logs and other operations .

4、Failback Cluster

Automatic recovery from failure , Failed requests are logged in the background , Timing to resend . Typically used for message notification operations .

5、Forking Cluster

Call multiple servers in parallel , Return as soon as one succeeds . It is usually used for reading operations with high real-time requirements , But more service resources need to be wasted .
It can be done by forks=”2” To set the maximum number of parallels .

6、Broadcast Cluster

Broadcast calls all providers , One by one call , If any channel reports an error, it will report an error .(2.1.0 Start supporting ) Usually used to notify all providers to update local resource information such as cache or log .

summary : in application Query statement The fault tolerance strategy recommends using the default Failover Cluster, and Additions and deletions It is recommended to use Failfast Cluster Or use Failover Cluster(retries=”0”) Strategy , Prevent data duplication and other problems ! When designing the interface, it is suggested that Make a separate interface Provide query .

How to connect

Dubbo There are three ways to connect the client and server of , Namely : radio broadcast 、 Direct connection And use Zookeeper Registry Center .

Dubbo radio broadcast

This way is dubbo The connection method used by the official entry program , But there are a lot of problems with this approach , Broadcast is not used in enterprise development .

Server configuration :

<!-- Preparation dubbo-->
<!-- Provide application information , Used to calculate dependencies -->
<dubbo:application name="demo-service"/>
<!-- Use multicast Broadcast registration service address -->
<dubbo:registry address="multicast://192.168.9.4:88888" />
<!-- Use dubbo The agreement 20880 Port exposure service -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- Declare exposed service interfaces -->
<dubbo:service interface="com.demo.manger.service.TestService" ref="testServiceImpl" />

Client configuration :

<!-- coordination dubbo-->
<!-- Provide application information , Used to calculate dependencies -->
<dubbo:application name="demo-web"/>
<!-- Use multicast Broadcast registry exposes service address  -->
<dubbo:registry address="multicast://19.188.8.9:8888"/>
<!-- Declare the interface that needs to be exposed -->
<dubbo:reference interface="com.demo.manager.service.TestService" id="testService" timeout="1000000" />

Dubbo Direct connection

This method is generally used in the development environment in enterprises , But production environments are rarely used , Because the service is called directly , Not using the registry , It's hard to manage services .Dubbo Direct connection , First, cancel the broadcast , And then the client goes directly to the url Just get the service .

Server configuration :

<!-- Preparation dubbo-->
<!-- Provide application information , Used to calculate dependencies -->
<dubbo:application name="demo-service"/>
<!-- Use multicast Broadcast registration service address -->
<-- <dubbo:registry address="multicast://192.168.9.4:88888" /> -->
<dubbo:registry adress="N/A">
<!-- Use dubbo The agreement 20880 Port exposure service -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- Declare exposed service interfaces -->
<dubbo:service interface="com.demo.manger.service.TestService" ref="testServiceImpl" />

Client configuration :

<!-- coordination dubbo-->
<!-- Provide application information , Used to calculate dependencies -->
<dubbo:application name="demo-web"/>
<!-- Use multicast Broadcast registry exposes service address  -->
<-- <dubbo:registry address="multicast://19.188.8.9:8888"/> -->
<!-- Declare the interface that needs to be exposed -->
<dubbo:reference interface="com.demo.manager.service.TestService" id="testService" timeout="1000000" url="dubbo://127.0.0.1:20880" />

zookeeper Registry Center

Dubbo The configuration of the registry is similar to that of the broadcast registry , But you need to specify the registry type and registry address , This is not the time to broadcast service information , But tell the registry to manage , At this time, we need to have a registry , The official recommendation Use zookeeper As a registry .

The registry is responsible for registering and finding service addresses , Equivalent to directory service , The service provider interacts with the registry at startup , Consumers are constantly asking for service information , The registry does not forward requests , Less pressure

Server configuration :

<!-- Preparation dubbo-->
<!-- Provide application information , Used to calculate dependencies -->
<dubbo:application name="demo-service"/>
<!-- Use multicast Broadcast registration service address -->
<!-- <dubbo:registry address="multicast://192.168.9.4:88888" /> -->
<!--<dubbo:registry adress="N/A"> -->
<dubbo:registry protocol="zookeeper" address="192.168.37,136:2181">
<!-- Use dubbo The agreement 20880 Port exposure service -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- Declare exposed service interfaces -->
<dubbo:service interface="com.demo.manger.service.TestService" ref="testServiceImpl" />

Client configuration :

<!-- coordination dubbo-->
<!-- Provide application information , Used to calculate dependencies -->
<dubbo:application name="demo-web"/>
<!-- Use multicast Broadcast registry exposes service address  -->
<-- <dubbo:registry address="multicast://19.188.8.9:8888"/> -->
<dubbo:registry protocol="zookeeper" address="192.168.37.1336:2181"/>    
<!-- Declare the interface that needs to be exposed -->
<dubbo:reference interface="com.demo.manager.service.TestService" id="testService" timeout="1000000" />

Strategy

Load balancing strategy

1、Random LoadBalance, Random ( Default load balancing strategy )

RandomLoadBalance It is the realization of weighted random algorithm , It can be completely random , You can also set random probabilities by weight .

2、RoundRobin LoadBalance, Rotation

It can be polled and weighted . There is a problem that slow responding providers accumulate requests , such as : The second machine is slow , But I didn't hang up , It's stuck when you ask for the second one , in the course of time , All requests are stuck on the second channel .

3、LeastActive LoadBalance, Minimum number of active calls

The smaller the number of active calls , Indicates that the service provider is more efficient , More requests can be processed per unit time . In this case, priority should be given to the service provider .

4、ConsistentHash LoadBalance, Uniformity Hash

Uniformity Hash Algorithm , Requests with the same parameters must be distributed to a provider Up .provider When I hang up , The remaining traffic will be evenly distributed based on the virtual node , It won't shake too much .

Cluster fault tolerance strategy

1、failover cluster( Default )

Fail auto switch , When the call fails , Automatically retry other machines . Usually used for read operations , But retrying brings longer delays .

2、Failfast Cluster
Fast failure , Make only one call , Failure reports an immediate error . Usually used for non idempotent write operations , For example, adding records .

3、Failsafe Cluster
Failure safety , When something unusual happens , Direct to ignore . Usually used to write audit logs and other operations .

4、Failback Cluster
Automatic recovery from failure , Failed requests are logged in the background , Timing to resend . Typically used for message notification operations .

5、Forking Cluster
Call multiple servers in parallel , Return as soon as one succeeds . It is usually used for reading operations with high real-time requirements , But more service resources need to be wasted .

Dynamic agent strategy

By default javassist Dynamic bytecode generation , Create a proxy class . It can also be done through spi The extension mechanism configures its own dynamic proxy strategy .

Cluster fault tolerance scheme

  • Configuration instructions , Scheme configuration mode , priority of use Consumer configuration

<!-- Server configuration -->
<dubbo:service cluster="failover"/>
<!-- Consumer configuration -->
<dubbo:reference cluster="failover"/>

  • Try to configure only on the server side

  • cluster All types are lowercase

  • The default is FailoverCluster Switching scheme failed

Cluster fault tolerance scheme support

FailoverCluster( Default ): Failed to switch

  • scene : After the call fails Switch Other services

  • To configure :

<!--
retries: Retry count , Not including the first time , Default 2 Time
-->
<dubbo:service cluster="failover" retries="3"/>

  • Code implementation logic :

    1. Select the service instance to call according to the load balancing strategy , Exclude called

    2. Execute the selected instance , And save it to the called list

    3. If the instance is executed successfully, it returns

    4. Execution instance failed , To achieve the maximum number of retries, perform the first step , Otherwise throw RpcException abnormal

FailbackCluster: Failure to retry

  • scene : When the call fails Record Failed request , Timing to resend

  • To configure :

<!--
retries: Retry count , Not including the first time , Default 3 Time
failbacktasks: Maximum number of pending tasks in timer , Default 100
-->
<dubbo:service cluster="failback" retries="5" failbacktasks="200"/>

  • Code implementation logic

    1. Select the service instance to call according to the load balancing strategy

    2. Execute the selected instance

    3. If the instance is executed successfully, it returns

    4. Execution exception creates delay 5 Second timing task , And add a time wheel timer , For the first time, it needs to be Timer initialization , It is divided into 32 Time slice , Every time 1 One second roll , The maximum pending task defaults to 100 individual , Thrown when the maximum number of tasks is exceeded RejectedExecutionException abnormal .

    5. Retrying scheduled tasks , The number of times exceeds the maximum number of execution , And the output error journal , The default is 3 Time .

FailfastCluster: Fast failure

  • scene : Call failed immediately Report errors

  • To configure :

<dubbo:service cluster="failfast"/>

  • Code implementation logic

    1. Select the service instance to call according to the load balancing strategy

    2. Execute the selected instance

    3. If the instance is executed successfully, it returns , Failure throw RpcException abnormal

FailsafeCluster: Security failure

  • scene : After the call fails Ignore

  • To configure :

<dubbo:service cluster="failsafe"/>

  • Code implementation logic

    1. Select the service instance to call according to the load balancing strategy

    2. Execute the selected instance

    3. If the instance is executed successfully, it returns , Failure output error journal , And back RpcResult, Regard as ignoring .

ForkingCluster: Concurrent processing

  • scene : Concurrent calls to a specified number of services , A success returns , Yes High real-time requirement Scene , Ask for a quick return , More server resources are needed .

  • To configure :

<!--
forks: Maximum number of concurrent , Default 2
timeout: Concurrent return timeout , Default 1000ms
-->
<dubbo:service cluster="forking" forks="3" timeout="500"/>

  • Code implementation logic

    1. Select several different service instances according to the load balancing strategy

    2. Concurrent execution of selected instances , And put the returned results into the blocking queue

    3. Returns the first value in the blocking queue , If the value in the queue is not obtained or the abnormal value is obtained within the specified time, return RPC abnormal .

BroadcastCluster: radio broadcast

  • scene : Broadcast mode calls service providers one by one , If an error is reported, an error is returned , It's mostly used to inform service providers to update Local resource information , Caching , Log etc. .

  • To configure :

<dubbo:service cluster="broadcast"/>

  • Code implementation logic

    1. The loop executes all service instance information one by one

    2. Save a copy of the returned results and exception information

    3. After executing all instances , If the exception information is not empty , Then throw an exception message , Otherwise, return the result of the last instance .

AvailableCluster: Available services

  • scene : call The first one is available service

  • To configure :

<dubbo:service cluster="available"/>

  • Code implementation logic

    1. Loop all service instance information

    2. Execute the first available instance , And return the result

    3. If no instance is available, return RpcException abnormal

MergeableCluster: Merge processing

  • scene : return Merge Or stack the processing results

  • To configure :

<!--
merger: Combined distribution name
timeout: Call service timeout , Default 1000ms
-->
<dubbo:service cluster="mergeable" merger="true" timeout="500"/>

  • Code implementation logic

    1. Judge merger, It's empty 、null、0、false、N/A Is to execute the first available service and return the result , If not available, execute the first instance , And return the result .

    2. Gets the return type of the method instance

    3. Call all instances asynchronously , And asynchronous results Result Store it in the result set , Returns the exception output error journal

    4. If the result set is empty, return RpcException, The size is 1 Return to the first Result

    5. When merger The first character of is “.” when , Judge when merger Does not return type for instance void, And the return type must be of the first return type in the result set Parent type or the same type when , Loop execution merger example , Each time, the last return result is passed in , Finally return to get the last result , If the above situation is not met, it will be executed circularly merger example , Returns the first result in the result set .

    6. When merger by true or default When using Dubbo Default combiner , Otherwise, use custom merger Combiner , Merge and return to

RegistryAwareCluster: The default ID 、 Sign up

  • scene : Call registration Default Services identified

  • To configure :

<!--
default: The default ID
-->
<dubbo:registry address="zookeeper://xxx..." default="true"/>
<dubbo:service cluster="registryaware"/>

  • Code implementation logic

    1.8 Loop all service instance information

    2. Execute the first available instance and default by true Example

    3. If there is no default instance, the first available instance is executed

    4. If no instance is available, throw RpcException abnormal

Main configuration

Configure application information :

<dubbo:application name=“appName-provider” />

Configure registry information :

<dubbo:registryid=“zk” protocol=“zookeeper” address=“127.0.0.1:2181” />

Configure the service agreement :

<dubbo:protocol name=“dubbo” port=“20880” threadpool=“cached” threads=“80” />

Configure all exposed service defaults :

<dubbo:provider registry=“zk” protocol=“dubbo” retries=“0” version=“1.0.0” timeout=“3000” threadpool=“cached” threads=“4”/>

Configure exposure Services :

<dubbo:service interface=“com.orgname.app.serviceX” ref=“serviceX” />

Configure all reference service defaults :

<dubbo:consumer check=“false” timeout=“1000” version=“1.0” retries=“0” async=“false” />

Annotation configuration :

com.alibaba.dubbo.config.annotation.Service  Configure exposure Services
com.alibaba.dubbo.config.annotation.Reference Configure the reference service 

timeout

Dubbo The consumer end

Global timeout configuration

<dubbo:consumer timeout="5000" />

Specify the interface and specific method timeout configuration

<dubbo:reference interface="com.foo.BarService" timeout="2000">
    <dubbo:method name="sayHello" timeout="3000" />
</dubbo:reference>

Dubbo Server side

Global timeout configuration

<dubbo:provider timeout="5000" />

Specify the interface and specific method timeout configuration

<dubbo:provider interface="com.foo.BarService" timeout="2000">
    <dubbo:method name="sayHello" timeout="3000" />
</dubbo:provider>

Support agreement

1、Dubbo agreement ( Official recommendation agreement )

advantage : use NIO Multiplexing a single long connection , And use thread pool to process requests concurrently , Reduce handshake and increase concurrent efficiency , Good performance ( Recommended )

shortcoming : A large file Upload time , There may be problems ( Don't use Dubbo Upload files )

2、RMI(Remote Method Invocation) agreement

advantage :JDK Bring their own The ability of . But with the original RMI interoperability , be based on TCP agreement

shortcoming : Occasionally the connection fails .

3、Hessian agreement

advantage : But with Native Hessian interoperability , be based on HTTP agreement

shortcoming : Need to be hessian.jar Support ,http Short connected * Spending big 8

Common design patterns

Dubbo The framework uses a variety of design patterns during initialization and communication , Flexible control Class loading 、 Access control And so on .

Factory mode

Provider stay export The service , Would call ServiceConfig Of export Method .ServiceConfig There is a field in :

private static final Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

Dubbo There's a lot of that code in there . It's also a factory model , It's just that the acquisition of the implementation class uses JDK SPI The mechanism of . The advantage of this is High scalability , Want to extend the implementation , Only need classpath Just add a file next , Code zero intrusion . in addition , Like above Adaptive Realization , You can dynamically decide which implementation to call when you call , But because this implementation uses dynamic agents , Can cause code debugging More trouble , We need to analyze the implementation class of the actual call .

Decorator mode

Dubbo The decorator pattern is heavily used in the startup and invocation phases . With Provider For example, the call chain provided , The specific call chain code is ProtocolFilterWrapper Of buildInvokerChain Accomplished , Specifically, the notes contain group=provider Of Filter Realization , according to order Sort , The last call sequence is :

EchoFilter -> ClassLoaderFilter -> GenericFilter -> ContextFilter ->
ExecuteLimitFilter -> TraceFilter -> TimeoutFilter -> MonitorFilter ->
ExceptionFilter

To be more exact , Here's the decorator and chain of responsibility model A mixture of . for example ,EchoFilter Is used to determine whether it is an echo test request , If yes, return the content directly , This is the embodiment of a responsibility chain . And like ClassLoaderFilter Only the main function is added , Change the... Of the current thread ClassLoader, This is a typical Decorator Pattern .

Observer mode

Dubbo Of Provider Startup time , Need to work with the registry Interaction , Register your service first , Subscribe to your own services , When subscribing , The observer model , To start a listener. The registration center will every 5 Seconds to check for service updates , If there is an update , Send a... To the provider of the service notify news ,provider Accept to notify After the news , I.e. operation NotifyListener Of notify Method , Execute listener method .

Dynamic proxy model

Dubbo Expand JDK SPI Class ExtensionLoader Of Adaptive Implementation is a typical dynamic agent implementation .Dubbo Need to control implementation classes flexibly , That is, in the call phase, which implementation class to call is dynamically determined according to the parameters , So using Mr. Cheng is an agent Methods , Be able to make flexible calls . The code to generate the proxy class is ExtensionLoader Of createAdaptiveExtensionClassCode Method . The main logic of the proxy class is , obtain URL The value of the parameter specified in the parameter is used to get the implementation class key

Workflow

Overall process :

First step :provider Go to the registry register

The second step :consumer Subscribe to services... From the registry , The registry will notice consumer Sign up for a good service

The third step :consumer call provider

Step four :consumer and provider all Asynchronous notification The monitoring center

summary

Finally, use a picture to simulate the image Dubbo Use :

These are just some of the things I've summarized about dubbo The most basic principle and use introduction , As for the coding process bug Dealing with experience , Environment building 、 Project layout and so on , We need to develop in peacetime , take System knowledge and practical experience To sum up , Only in this way can we really master this technology .

Dubbo It's the most distributed framework I've ever used , The content written is also the most , But due to the Dubbo Too much , and SpringCloud Difficulty ratio Dubbo It's a lot smaller , Now most of the projects are about to start to switch to SpringCloud above , There will be more in the future SpringCloud Related articles .