Spring Boot Build Application--integrated Dubbo framework _spring-boot

Source: Internet
Author: User
Tags naming convention serialization zookeeper

Dubbo is an open source distributed service framework dedicated to providing high-performance and transparent RPC remote service invocation scenarios and SOA service governance scenarios. Dubbo uses a full Spring configuration, transparent access applications, no API intrusion on the application, just use spring to load the Dubbo configuration, Dubbo load based on the Schema extension of spring. The registration center recommended by Dubbo is zookeeper.

Call Relationship Description:
1, the service container is responsible for starting, loading, running service providers, service providers at the start of the registration center to register their own services provided;
2, service consumers in the start-up, to the registry to subscribe to their own services required;
3, the Registration center returns the service provider address list to the consumer, if has the change, the registration center will push the change data to the consumer based on the long link;
4, service consumers, from the provider address list, based on the soft load equalization algorithm, select a provider to make calls, if the call fails, and then select another call;
5, service consumers and providers, in memory of the cumulative number of calls and call time, timed every minute to send statistical data to the monitoring center.

Dubbo architecture has the following characteristics: Dubbo characteristics of Connectivity 1 Registration center is responsible for the registration and lookup of service addresses, the equivalent of directory services, service providers and consumers only at the start of the interface with the registry, the registry does not forward requests, less pressure;
2 The Monitoring Center is responsible for statistics of the number of service calls, call time, statistics first in memory after the summary sent to the Monitoring center server every minute, and to show the report;
3 The service provider registers its services with the registry and reports the call time to the Monitoring center, which does not include network overhead;
4 The service consumer obtains the service provider address list to the registration center, and invokes the provider directly according to the load algorithm, and reports the call time to the Monitoring center, which includes the network overhead;
5 The Registration center, the service provider, the service consumer three are the long connection, except the Monitoring center;
6 The registration center through Long connection aware service provider's existence, service provider downtime, the registry will immediately push the event to notify consumers;
7 The Registration center and the Monitoring Center all downtime, does not affect the already running provider and the consumer, the consumer caches the provider list locally;
8 The registration center and the Monitoring center are optional, the service consumer can direct connect the service provider. Fitness 1) Monitoring center downtime does not affect the use of, but lost part of the sampling data;
2 after the database is down, the registry can still provide a list of services through the cache, but can not register new services;
3 Registration Center peer cluster, any one after the outage, will automatically switch to another;
4 The service provider and the service consumer can still communicate through the local cache after the registration center is completely down;
5 The service provider has no state, any one after the outage, does not affect the use;
6 when the service provider is completely down, the service consumer application will be unusable and the service provider can be restored indefinitely. Scalability 1) Registration Center for the peer cluster, can dynamically increase the machine deployment instances, all clients will automatically discover the new registry center;
2 The service provider has no status, can dynamically increase the machine deployment instance, the registry will push the new service provider information to the consumer. Upgrade when the scale of the service cluster expands further, it promotes the IT governance structure, it needs to realize dynamic deployment, flow calculation, the existing distributed service architecture will not bring resistance. The following diagram is a possible architecture for the future:
Node role Description:
Deployer: Local agent for the Automated deployment service
Repository: Warehouse for Storage Service Application Publishing package
Scheduler: Dispatch center automatically increases and decreases service providers based on access pressure
Admin: Unified Management Console
Registry: Registration Center for service Registration and discovery
Monitor: The monitoring Center for the number of calls and time to count services

The Dubbo core is as follows: Dubbo Core Description Remote communications provides a variety of long connected NIO framework abstraction packages, including multiple threading models, serialization, and "request-response" mode of information interchange cluster fault tolerant provides transparent remote procedure calls based on interface methods, including Multi-Protocol support, As well as soft load balancing, failure fault tolerance, address routing, dynamic configuration, such as cluster support automatic discovery based on registry directory services, so that service consumers can dynamically find service providers, so that the address transparent, so that service providers can smooth increase or reduce the machine

The Dubbo Protocol (DUBBO://) is recommended for Dubbo communication protocols. The Dubbo protocol uses a single long connection and NIO asynchronous communication, using tbremoting interaction based on Mina 1.1.7 and Hessian 3.2.1. It is suitable for service invocation with small data volume concurrency, and the number of service consumer machines is much larger than the number of service provider machines. Conversely, the Dubbo protocol is not suitable for the delivery of large amounts of data services, such as file transfer, video transmission, unless the request is very low.

dubbo://Description Connection Number single connection connection way long connection transport protocol TCP transmission mode NIO Asynchronous transport serialization Hessian binary serialization application range incoming outgoing parameter packet smaller (less than 100K recommended), consumers more than the provider, single consumers can not fill the provider , try not to transfer large files or oversized strings using the Dubbo protocol. Applicable Scenarios General remote service method invocation

About Dubbo Management Console installation (Dubbo Management Console is the main role of service governance, including service registration, service demotion, routing rules, Access control, dynamic configuration, weight adjustment, load balancing, service owner, and other management functions. Please install the Dubbo Management console under Linux. 1.Spring Boot Integration Dubbo

Service providers (provider) and consumers (consumer) all need to add Maven dependencies:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactid>dubbo</artifactid >
    <version>2.6.1</version>
    <exclusions>
        <exclusion>
            <groupId> org.springframework</groupid>
            <artifactId>spring-context</artifactId>
        </exclusion >
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId> spring-beans</artifactid>
        </exclusion>
        <exclusion>
            <groupId> org.springframework</groupid>
            <artifactId>spring-web</artifactId>
        </exclusion >
    </exclusions>
</dependency>
<dependency>
    <groupId> org.apache.curator</groupid>
    <artifactId>curator-framework</artifactId>
    < Version>2.12.0</version>
</dependency>
1. Service Interface (API)

APIs (Service interfaces, service models, service exceptions) need to be packaged separately, and service providers and consumers rely on APIs. The API hides the implementation of the consumer side of the service. Down to define the unified service interface (if the Pojo,pojo is returned, the Serializable interface must be implemented):

Public interface Demoservice {
    string SayHello (string name);
}
2. Service Provider (Provider)

To implement an interface on a service provider:

Import Org.springframework.stereotype.Service;
@Service public
class Demoserviceimpl implements Demoservice {
    @Override public
    string SayHello (string Name {return
        "Hello," + name;
    }
}

Configure Consumer-side properties as much as possible on the Provider, and after Provider configuration, Consumer does not configure the Provider configuration value, that is, the Provider configuration can be used as the default value for Consumer. Otherwise, Consumer will use the global setting on the Consumer side, which is not controllable for Provider, and is often unreasonable. Consumer-side properties that can be configured on Provider are: Property Description Timeout method call timeout. Retries failed retry count, default is 2. LoadBalance load Balancing algorithm, the default is random random, there can be polling roundrobin, the least active priority leastactive. Actives the maximum concurrent invocation limit on the consumer side, the default is 0, not limited. That is, when a concurrent call to a service is Consumer to the upper limit, the new call waits until it times out.

Spring Configuration Declaration Exposure Service (Resources/spring-dubbo-provider.xml):

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo= "Http://code.alibabatech.com/schema/dubbo" Xsi:sch emalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd " > <!--provider application information for computing dependencies--> <dubbo:application name= "Demo-provider"/> <!--use zookeeper registry to expose Service address--> <dubbo:registry client= "curator" protocol= "Zookeeper" address= "192.168.1.2:2181,192.168.1.3:2181"/  > <!--Dubbo Protocol 20880-Port exposure--> <dubbo:protocol name= "Dubbo" port= "20880"/> <!--declaration of service interfaces to be exposed
            --> <dubbo:service interface= "Com.example.demo.service.DemoService" version= "1.0.0" ref= "Demoserviceimpl" timeout= "1000" retries= "2" loadbalance= "random" actives="0"/> </beans> 

To load the Spring configuration:

Import Org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource ("Classpath:spring-dubbo-provider.xml") Public
class providerapplication {public
    static void Main (string[] args) {
        Springapplication.run ( Providerapplication.class, args);
    }
3. Service Consumer (Consumer)

Referencing a remote service (Resources/spring-dubbo-consumer.xml) through the Spring configuration:

<?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.xsd Http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/ Dubbo.xsd ">
    <!--consumer application name, used to compute dependencies, not matching criteria, not-->
    <dubbo:application name=" Demo-consumer "/ >
    <!--Use zookeeper registry to expose Discovery service address-->
    <dubbo:registry client= "curator" protocol= "Zookeeper" address= "192.168.1.2:2181,192.168.1.3:2181"/>
    <!--generate a remote service proxy that can be used like a local bean Demoservice-->
    < Dubbo:reference id= "Demoservice" interface= "Com.example.demo.service.DemoService" version= "1.0.0"/> </
Beans>

To load the spring configuration:

Import Org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource ("Classpath:spring-dubbo-consumer.xml") Public
class consumerapplication {public
    static void Main (string[] args) {
        Springapplication.run ( Consumerapplication.class, args);
    }

To invoke a remote service:

Import Javax.annotation.Resource;
@RestController public
class Democontroller {
    @Resource
    private demoservice demoservice;
    @RequestMapping ("/sayhello") public
    String SayHello (@RequestParam string name) {
        return Demoservice.sayhello (name);
    }

To this integration, run the Provider and Consumer projects, the browser access to Consumer external delivery of the RESTful API, you can successfully invoke the remote service. Here we can also see that Dubbo has no API intrusion on the application. Official Schema Configuration reference manual. 2. Service Best Practices-Description Granularity 1 service interface as large as possible, each service method should represent a function, rather than a function of a step, otherwise will face a distributed transaction issues, Dubbo temporarily provides distributed transaction support;
2 The service interface is proposed to divide the business scene, and to abstract the close business to prevent the number of interfaces exploding. Version 1 each interface should have a version number defined to provide the possibility for subsequent incompatible upgrades;
2) It is recommended to use the two-bit version number because the third-digit version number usually indicates a compatible upgrade and only needs to change the service version if it is incompatible;
3 when incompatible, upgrade the first half of the provider to the new version, then all the consumers to the new version, and then the remaining half of the provider to the new version. Exception 1) Recommends using exception reporting errors instead of returning error codes, which can carry more information and are more semantically friendly.
2 If you are concerned about performance problems, if necessary, you can override the Exception class Fillinstacktrace () method is empty method, so that it does not copy stack information.
3 The Query method does not recommend throwing checked exceptions, otherwise the caller will be overly try...catch when querying and cannot be processed effectively.
4 The service provider should not throw the DAO or SQL exception to the consumer, should be in the service implementation of the consumer does not care about the exception packaging, or may be the consumer can not deserialize the corresponding exception. 3. Deploy the Dubbo service on Linux

To deploy the directory specification (to avoid path conflicts when migrating is applied):

/home/wwwroot/example/
                |/app             //Deployment App
                     |-/app1
                     |/app2
                |-/service         //Deploy Distributed Services
                     |      Order//Orders Service
                     |-/queue      //Message Queuing Service |-/user//       User Service
                |-/timer           //Deploy timed Tasks
                     |-/report     //Report
                |/web             //Deployment Web Project
                     | |-/gateway
                     |/operation
                     |-/portal

Manual maintenance of Dubbo Services (sometimes a mapping error is reported, host name IP mapping can be configured via Vim/etc/hosts):

# Java-jar Xxx.jar &/                       start Service

# nohup Java-jar Xxx.jar &                 //Gazhi boot
# tail-f nohup.out                         /view Start Log

# Ps-ef | grep java                        //First number is PID
# kill PID                                  //Kill service
# kill-9 PID

Customizing Shell scripts for Dubbo Service maintenance (naming convention:/home/wwwroot/example/xxx/service-xxx.sh):

#!/bin/sh # java ENV export JAVA_HOME=/USR/LOCAL/JDK export jre_home= $JAVA _home/jre # # service Name App_name=user serv
ice_dir=/home/wwwroot/example/service/$APP _name service_name=dubbo-service-$APP _name JAR_NAME= $SERVICE _name\.jar pid= $SERVICE _name\.pid cd $SERVICE _dir case "in Start" # # debug:-xms256m-xmx512m,formal:-xms512m-xmx204 8m nohup $JRE _home/bin/java-xms256m-xmx512m-jar $JAR _name >/dev/null 2>&1 & Echo $!

    > $SERVICE _dir/$PID echo "= = = Start $SERVICE _name";

        stop) Kill ' cat $SERVICE _dir/$PID ' rm-rf $SERVICE _dir/$PID echo = = = Stop $SERVICE _name Sleep 5 # # # Dubbo-service-aa.jar # # Dubbo-service-aa-bb.jar p_id= ' Ps-ef | Grep-w "$SERVICE _name" | Grep-v "grep" | awk ' {print $} ' if [' $P _id ' = ']; then echo "= = = $SERVICE _name process not exists or stop success" else echo "= = = $SERVICE _naME process pid is: $P _id "echo" = = Begin kill $SERVICE _name process, PID is: $P _id "Kill-9 $P _id

    fi;;

    Restart) $ Stop Sleep 2 $ start echo "= = = Restart $SERVICE _name";;

*) # # Restart $ stop sleep 2 $ start;; ESAC Exit 0
 # cd/home/wwwroot/example/service/user # chmod 777 *.sh//switch to root, assign executable permissions to *.sh #./se rvice-user.sh Start #/service-user.sh Stop #/service-user.sh Restart # Ps-ef | grep Java//view run status 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.