13, Spring technology stack-integration Dubbo, zookeeper to achieve highly available distributed micro-service Combat _ Distributed

Source: Internet
Author: User
Tags aop zookeeper zookeeper client

In the spring technology stack-consolidation Dubbo, Zookeeper we've talked about how to integrate Spring, Dubbo, and zookeeper to develop a distributed application. This article is based on the above to describe how to package the deployment of Dubbo Micro services to achieve a highly available micro-service cluster, if you do not know how to integrate Spring, Dubbo, zookeeper, please read the above, and then read this article for the micro-service packaging and deployment operations.

preparatory work

We assume that readers have installed the necessary basic software in their environment, such as the Maven,java JDK, and this article does not describe how to install these infrastructure artifacts, only the packaging, deployment, and running test scenarios for deploying Dubbo Micro services.

Install Virtual machine 3, the author installs the virtual machine to use is VirtualBox, the reader may according to own environment concrete analysis, installs completes after the virtual machine, wants to ensure that the virtual machine and host hosts can carry on the network communication.

IP Notes Open Ports
192.168.199.177 (host) MySQL is installed in the host 3306 (need to add the inbound rule, the 3306 port open, otherwise the virtual machine can not link MySQL)
192.168.199.161 (virtual machine) Zookeeper Registration Center 2181
192.168.199.249 (virtual machine) Service Host 20882
192.168.199.126 (virtual machine) Service Host 20882

The above is the author machine installed on the virtual machine information, only for reference, the reader can be based on their specific environment specific installation.

Example Introduction

To develop a blog service, for example, when users visit the blog list, we start by starting two service instances to register to zookeeper, then let one of the services down, and then test the blog list for normal access.

Service Interface

Public interface Blogfacade {
    /**
     * @Comment Get blog list
     * @Author Ron
     * @Date October 25, 2017 pm 2:53:39
     * @re Turn
     * *
    list<blogcontent> findbloglist (blogcontent blogcontent);

    /**
     * @Comment Get Blog Content
     * @Author Ron
     * @Date October 25, 2017 afternoon 3:04:57
     * @return
    * * Blogcontent Getblog (String bid);

Service Implementation

Create a new Blog_service project, new Blogservice implement the above interface

@Component ("Blogservice") public class Blogservice implements blogfacade{private Logger Logger = Logmanager.getlogge

    R (This.getclass ());

    @Autowired private Blogcontentmapper Blogcontentmapper;  

    @Autowired redisutils redisutils;
    /** * @Comment Get Blog list * @Author Ron * @Date October 25, 2017 afternoon 3:04:01 * @return * * @Override
        Public list<blogcontent> findbloglist (blogcontent blogcontent) {logger.info ("Enter blog query list");
        try {return blogcontentmapper.selectlist (blogcontent);
            catch (Exception e) {logger.error ("Access blog list failed" +e);
        return null; /** * @Comment Get Blog content * @Author Ron * @Date October 25, 2017 afternoon 3:05:27 * @return * Override public blogcontent Getblog (String Bid) {if redisutils.exists (Bid)) {logger.info (Cache hit blog)
            +bid);
        Return (blogcontent) redisutils.get (BID); }else{LOgger.info ("Cache not hit blog" +bid);
            Blogcontent blogcontent = blogcontentmapper.selectbyprimarykey (BID);
            Redisutils.set (bid, blogcontent);
        return blogcontent; }
    }
}

In the service instance we use the Redis to do the cache, the reader can refer to 12, Spring technology stack-redis Sentinel the article understands how to use Redis to implement the cache cluster.

The Blogcontentmapper is a mapping class that integrates MyBatis access to MySQL, and on how to integrate MyBatis, readers can refer to the 2, spring technology stack-consolidation MyBatis

Dubbo Service Provider Configuration

Add the Dubbo directory to the Resources directory, create a new dubbo.xml, and write the following

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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.x SD "> <dubbo:application name=" ron-service-blog "logger=" log4j "/> <dubbo:registry protocol=" zookeeper "Address=" ${registry.address} "/> <dubbo:monitor protocol=" registry "/> <dubbo:protocol name=" Dubb
        O "port=" ${service.port} "serialization=" Java "/> <dubbo:provider timeout=" 30000 "loadbalance=" random "> <dubbo:parameter key= "Shutdown.timeout" value= "60000"/> <dubbo:parameter key= "Shutdown.hook" Val Ue= "true"/> <dubbo:parameter key= "Retries" value= "0"/> </dubbo:provider> <!--Declare services that need to be exposed--> <dubbo:service interf Ace= "Ron.blog.blog_facade.blog.BlogFacade" ref= "Blogservice"/> </beans>

config.properties Configuration

In the configuration file, increase the zookeeper address and port and the service port configuration.

#zookeeper配置
registry.address=192.168.199.161:2181
service.port=20882

Micro-Service project Pom.xml configuration

In addition to adding Dubbo and zookeeper client dependencies in the service's Pom.xml file, we need to add some maven plug-ins to help us copy the dependent jar packages and associated resource files to the specified directory when using MAVEN to package the project. At the same time because we developed the micro-service general situation home is a jar package, so we need this jar package to be able to run the document, so we also need in the Pom file to specify the location of the main function (program entry). The specific configuration is as follows:

dubbo_version:2.8.4a
zkclient_version:0.10

    <!--Dubbo--> <dependency> <groupId>com.alibaba</groupId> <artifactid& Gt;dubbo</artifactid> <version>${dubbo_version}</version> </dependency> <!--zo Okeeper--> <dependency> <groupId>com.101tec</groupId> <artifactid>zkclient
        </artifactId> <version>${zkclient_version}</version> </dependency> <build>
            <finalName>ron-service-blog</finalName> <resources> <!--resource file-->
                <resource> <targetPath>${project.build.directory}/classes</targetPath>
                <directory>src/main/java</directory> <filtering>true</filtering>
            <includes> <include>**/*.xml</include> </includes>
</resource>            <resource> <!--The object directory of the copy of the profile--> <targetpath>${project.build.d
                Irectory}/classes</targetpath> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.xml</
            Include> <include>**/*.properties</include> </includes> </resource> <resource> <!--profile must be placed under the Spring folder, otherwise Dubbo does not actually start successfully even if the display starts successfully--&
                Gt <targetPath>${project.build.directory}/classes/META-INF/spring</targetPath> <directory>s Rc/main/resources/</directory> <filtering>true</filtering> <includes&
                    Gt <include>spring-context.xml</include> </includes> </resource> </resources> <plugins> <plugin> <groupid>o
                Rg.apache.maven.plugins</groupid> <artifactId>maven-jar-plugin</artifactId>
                    <configuration> <classesDirectory>target/classes/</classesDirectory> <archive> <manifest> <mainclass>com.alibaba .dubbo.container.main</mainclass> &LT;USEUNIQUEVERSIONS&GT;FALSE&LT;/USEUNIQUEVERSIONS&G
                            T <addClasspath>true</addClasspath> <classpathprefix>lib/</classpathprefix&
                        Gt </manifest> <manifestEntries> <class-path>.</clas S-path> </manifestEntries> </archive> </configuration> </plugin> <plugin> &L T;groupid>org.apache.maven.plugins</groupid> <artifactid>maven-dependency-plugin</artifa ctid> <executions> <execution> <id>copy-d
                            Ependencies</id> <phase>package</phase> <goals>
                        <goal>copy-dependencies</goal> </goals> <configuration> <type>jar</type> <i
                                Ncludetypes>jar</includetypes> <outputDirectory> ${project.build.directory}/lib </outputDirectory> </configu
             Ration>       </execution> </executions> </plugin> </plugins> ;/build>

Dubbo Consumer Configuration

Create a new Dubbo directory in the resources directory on the Web side, add the Dubbo.xml file, and write the following.

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:jdbc=" Http://www.springframework.org/schema/jdbc "xmlns:context= "Http://www.springframework.org/schema/context" xmlns:dubbo= "Http://code.alibabatech.com/schema/dubbo" xsi: schemalocation= "Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.0.xsd Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.0.xsd Http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/ Spring-jdbc-4.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.orG/schema/aop/spring-aop-4.0.xsd Http://code.alibabatech.com/schema/dubbo Http://code.alibabatech.com/schema/dubb

    O/dubbo.xsd "> <!--consumer application name, used to compute dependencies, not matching criteria, not--> <dubbo:application name=" Blog-service "/> <context:property-placeholder ignore-unresolvable= "true" location= "Classpath:config.properties"/> <!-- Use the Zookeeper registry to expose service addresses--> <dubbo:registry protocol= "zookeeper" address= "${registry.address}"/> <dubb O:consumer check= "false"/> <!--service Application--> <dubbo:reference id= "Blogservice" interface= _facade.blog.blogfacade "/> </beans>

Where the configuration parameters are added to the config.properties, the contents are as follows

#zookeeper配置
registry.address=192.168.199.161:2181

packaged Blog_service Micro service

In the command-line tool, go to the project Pom.xml file directory and package with the following command

MVN Clean
mvn package-dmaven.test.skip=true

After the package is complete, we will see a *.jar package and a Lib folder in the target directory of the project, and only the jar and Lib folders need to be uploaded when deployed.

Installing and configuring Zookeeper

Install zookeeper as a service registration center, This article installs the zookeeper on 192.168.199.161 this virtual machine, zookeeper installs see Zookeeper Essence-standalone mode, this article mainly describes the service high availability, the registration center we adopt the single point can.

Note: The address and port of the registry specified by the service must be the address and port of the virtual machine where the zookeeper you are installing.

#zookeeper配置
registry.address=192.168.199.161:2181
#服务端口
service.port=20882

Deployment Services

We assume that the reader has installed the Java environment on its own virtual machine, so this does not explain how to install the Java environment.

In the service host (the author's service host is 192.168.199.126, 192.168.199.249) to create a new directory for the storage of service-related files.

Mkdir/data/blogsrv

Through the FTP tool will be packaged content uploaded to the directory, the author is using Filezilla.exe. After the file is uploaded, write the startup script.

New start.sh, file, write startup script.

Cd/data/blogsrv
VI start.sh

Write the following in start.sh

#!/bin/bash
nohup Java-jar ron-service-blog.jar > Nohup.log 2>&1 &

Explain the meaning of the startup script command: Running the service in the background and outputting the service's error flow information as a standard output stream into the Nohup.log file.

Give start.sh script read and Write permissions

chmod 777 start.sh

Start a service

Use the following command on the service host to perform the startup script startup service separately.

Cd/data/blogsrv
./start.sh

Once the service has started successfully, you can see if it started successfully with the following command

Ps-ef|grep Ron-service-blog (here is the name of the jar package)

If you start successfully, you will see the following

[Root@localhost blogsrv]# ps-ef|grep ron-service-blog
root      4193     1  0 14:09 pts/0 00:00:29    java- Jar Ron-service-blog.jar
root      4348  2316  0 15:25 pts/0    00:00:00 grep--color=auto Ron-service-blog

If startup fails, the directory stored in the service jar package generates a Nohup.log file, and the reader can view the contents of the log file to view the error message and fix it.

Service Availability Testing

If the services on both machines are successfully started, we can open our service consumer side, the peer-Test Blog page can be accessed.

Next we go to any one of the virtual machines that deploys the service, kill the service process using the KILL command, refresh the page again, and the blog list page is still available.

Re-refresh the page

System Source: http://download.csdn.net/download/zyhlwzy/10122870

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.