Distributed services framework Dubbo / dubbox getting started example

mb60f93b6c4c5e3 2021-07-28 22:09:23
distributed services framework dubbo dubbox


dubbo It's a distributed service architecture , It can be directly used in production environment as SOA Service Framework .

Website home page :http://dubbo.io/ , Official User Guide  http://dubbo.io/User+Guide-zh.htm The pictures above are good , It can be regarded as SOA Structured learning materials

After Taobao open source this project , It has won the support of many peers , Include :

An extended version of Dangdang dubbox :https://github.com/dangdangdotcom/dubbox

 

however , It's a little pity that , It is said that inside Taobao ,dubbo Because of another similar framework with Taobao HSF( Non open source ) It's competitive , Lead to dubbo The team has been disbanded , On the contrary, the extended version of Dangdang is still developing , Flowers in the wall, fragrance outside the wall .

No matter how , In Ali 、 Dangdang 、 Jingdong is a framework officially used by these large websites , It's not so bad .

The following examples in this article are based on Dangdang's dubbox edition , because dubbox Not to maven Submit the compiled jar package , So only from github clone The code is compiled locally to get jar package .

 

Compilation and test steps :( The following steps are all in windows In the environment )

1.  This machine is installed first github on Windows The client of , Will be in path In the path , hold git.exe add

2.  At the command line  git clone https://github.com/dangdangdotcom/dubbox  Pull the code locally

3. mvn install -Dmaven.test.skip=true Skip test compilation

4.  In this machine To install a zookeeper, Reference resources zoo.cfg as follows :

tickTime=2000
initLimit=10
syncLimit=5
dataDir=D:/java/zookeeper-3.4.6/data
dataLogDir=D:/java/zookeeper-3.4.6/log
clientPort=2181
server.1=localhost:2287:3387

Then input bin/zkServer.cmd Enable zookeeper

5. intellij Idea In the import source

6.  function  \dubbox\dubbo-demo\dubbo-demo-provider\src\test\java\com\alibaba\dubbo\demo\provider\DemoProvider.java 

Run the service provider , After success , Can be in ZK in , use ls / look down , Will find zk There is one more in the dubbo The node of , All services are registered here

7.  function \dubbox\dubbo-demo\dubbo-demo-consumer\src\test\java\com\alibaba\dubbo\demo\consumer\DemoConsumer.java

The service consumer invokes the test , You can see console The output in

8.  function \dubbox\dubbo-demo\dubbo-demo-consumer\src\test\java\com\alibaba\dubbo\demo\consumer\RestClient.java

Run rest call

9.  Browser access  http://localhost:8888/services/users/100.xml or  http://localhost:8888/services/users/100.json

 

dubbox Official examples , It's very simple , But for people who come into contact for the first time , Still a little complicated , The following code simplifies it :

One 、 First define the service interface and transmission object DTO

The project structure is as follows

Code :

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package  yjmyzz.dubbo.demo.api;
import  org.codehaus.jackson.annotate.JsonProperty;
import  javax.validation.constraints.Min;
import  javax.validation.constraints.NotNull;
import  javax.validation.constraints.Size;
import  javax.xml.bind.annotation.XmlAccessType;
import  javax.xml.bind.annotation.XmlAccessorType;
import  javax.xml.bind.annotation.XmlElement;
import  javax.xml.bind.annotation.XmlRootElement;
import  java.io.Serializable;
 
@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public  class  User  implements  Serializable {
 
     @NotNull
     @Min (1L)
     private  Long id;
 
     @JsonProperty ( "username" )
     @XmlElement (name =  "username" )
     @NotNull
     @Size (min =  6 , max =  50 )
     private  String name;
 
     public  User() {
     }
 
     public  User(Long id, String name) {
         this .id = id;
         this .name = name;
     }
 
     public  Long getId() {
         return  id;
     }
 
     public  void  setId(Long id) {
         this .id = id;
     }
 
     public  String getName() {
         return  name;
     }
 
     public  void  setName(String name) {
         this .name = name;
     }
 
     @Override
     public  String toString() {
         return  "User ("  +
                 "id="  + id +
                 ", name='"  + name + '\ ''  +
                 ')' ;
     }
}

UserService.java

1
2
3
4
5
package  yjmyzz.dubbo.demo.api;
 
public  interface  UserService {
     User getUser(Long id);
}

UserRestService.java

1
2
3
4
5
6
7
package  yjmyzz.dubbo.demo.api;
 
import  javax.validation.constraints.Min;
 
public  interface  UserRestService {
     User getUser( @Min (value = 1L, message =  "User ID must be greater than 1" ) Long id);
}

pom.xml

 Copy code
 1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
6 <modelVersion>4.0.0</modelVersion>
7
8 <groupId>com.cnblogs.yjmyzz</groupId>
9 <artifactId>dubbo-hello-api</artifactId>
10 <version>0.1</version>
11
12 <dependencies>
13
14 <dependency>
15 <groupId>com.alibaba</groupId>
16 <artifactId>dubbo</artifactId>
17 <version>2.8.4</version>
18 </dependency>
19
20 <dependency>
21 <groupId>javax.validation</groupId>
22 <artifactId>validation-api</artifactId>
23 <version>1.0.0.GA</version>
24 </dependency>
25
26 <dependency>
27 <groupId>javax.annotation</groupId>
28 <artifactId>javax.annotation-api</artifactId>
29 <version>1.2</version>
30 </dependency>
31
32 <dependency>
33 <groupId>org.codehaus.jackson</groupId>
34 <artifactId>jackson-mapper-asl</artifactId>
35 <version>1.9.12</version>
36 </dependency>
37
38 </dependencies>
39 </project>
 Copy code

 

Two 、 Defining service producers ( namely : The implementer of the service interface )

UserServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
package  yjmyzz.dubbo.demo.provider;
 
import  yjmyzz.dubbo.demo.api.User;
import  yjmyzz.dubbo.demo.api.UserService;
 
public  class  UserServiceImpl  implements  UserService {
 
     public  User getUser(Long id) {
         return  new  User(id,  "username"  + id);
     }
}

UserRestServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package  yjmyzz.dubbo.demo.provider;
 
import  com.alibaba.dubbo.rpc.RpcContext;
import  com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import  yjmyzz.dubbo.demo.api.User;
import  yjmyzz.dubbo.demo.api.UserRestService;
import  yjmyzz.dubbo.demo.api.UserService;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
import  javax.ws.rs.*;
import  javax.ws.rs.core.MediaType;
 
@Path ( "users" )
@Consumes ({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces ({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public  class  UserRestServiceImpl  implements  UserRestService {
 
     private  UserService userService;
 
     public  void  setUserService(UserService userService) {
         this .userService = userService;
     }
 
     @GET
     @Path ( "{id : \\d+}" )
     public  User getUser( @PathParam ( "id" ) Long id) {
         if  (RpcContext.getContext().getRequest(HttpServletRequest. class ) !=  null ) {
             System.out.println( "Client IP address from RpcContext: "  + RpcContext.getContext().getRequest(HttpServletRequest. class ).getRemoteAddr());
         }
         if  (RpcContext.getContext().getResponse(HttpServletResponse. class ) !=  null ) {
             System.out.println( "Response object from RpcContext: "  + RpcContext.getContext().getResponse(HttpServletResponse. class ));
         }
         return  userService.getUser(id);
     }
}

DemoProvider.java

1
2
3
4
5
6
7
8
9
10
11
12
package  yjmyzz.dubbo.demo.provider;
import  org.springframework.context.support.ClassPathXmlApplicationContext;
import  java.io.IOException;
 
public  class  DemoProvider {
     public  static  void  main(String[] args)  throws  IOException {
         ClassPathXmlApplicationContext context =  new  ClassPathXmlApplicationContext( "classpath*:META-INF/spring/*.xml" );
         context.start();
         System.out.println( " Service started ..." );
         System.in.read();
     }
}

The configuration file :resources\META-INF\spring\dubbo-demo-provider.xml

Press Ctrl+C Copy code
Press Ctrl+C Copy code

pom.xml

Press Ctrl+C Copy code
Press Ctrl+C Copy code

When testing , function DemoProvider Medium main Method to start the service , All services are registered at ZooKeeper, The hierarchy is similar to the following :

 Copy code
/dubbo
/dubbo/yjmyzz.dubbo.demo.api.UserRestService
/dubbo/yjmyzz.dubbo.demo.api.UserRestService/providers
/dubbo/yjmyzz.dubbo.demo.api.UserRestService/configurators
/dubbo/yjmyzz.dubbo.demo.api.UserService
/dubbo/yjmyzz.dubbo.demo.api.UserService/providers
/dubbo/yjmyzz.dubbo.demo.api.UserService/configurators
 Copy code

 

3、 ... and 、 Service consumer

 

DemoConsumer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package  yjmyzz.dubbo.demo.consumer;
 
import  org.springframework.context.support.ClassPathXmlApplicationContext;
import  yjmyzz.dubbo.demo.api.UserService;
import  javax.ws.rs.client.Client;
import  javax.ws.rs.client.ClientBuilder;
import  javax.ws.rs.client.WebTarget;
import  javax.ws.rs.core.Response;
 
public  class  DemoConsumer {
 
     public  static  void  main(String[] args) {
         final  String port =  "8888" ;
 
         // test Rest service
         getUser( "http://localhost:"  + port +  "/services/users/1.json" );
         getUser( "http://localhost:"  + port +  "/services/users/1.xml" );
 
         // Test regular services
         ClassPathXmlApplicationContext context =  new  ClassPathXmlApplicationContext( "classpath*:META-INF/spring/*.xml" );
         context.start();
         UserService userService = context.getBean(UserService. class );
         System.out.println(userService.getUser(1L));
     }
 
 
     private  static  void  getUser(String url) {
         System.out.println( "Getting user via "  + url);
         Client client = ClientBuilder.newClient();
         WebTarget target = client.target(url);
         Response response = target.request().get();
         try  {
             if  (response.getStatus() !=  200 ) {
                 throw  new  RuntimeException( "Failed with HTTP error code : "  + response.getStatus());
             }
             System.out.println( "Successfully got result: "  + response.readEntity(String. class ));
         finally  {
             response.close();
             client.close();
         }
     }
}

The configuration file :resources\META-INF\spring\dubbo-hello-consumer.xml

 Copy code
 1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
6 http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
7
8 <dubbo:application name="demo-consumer" owner="programmer" organization="dubbox"/>
9
10 <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
11
12 <dubbo:reference id="userRestService" interface="yjmyzz.dubbo.demo.api.UserRestService"/>
13
14 <dubbo:reference id="userService" interface="yjmyzz.dubbo.demo.api.UserService"/>
15
16 </beans>
 Copy code

pom.xml

Press Ctrl+C Copy code
Press Ctrl+C Copy code

Other precautions :

dubbo In architecture ,zk Filled with “ Service registry ” Role , So the relationship between producers and consumers xml In profile , All have to be configured zk Address , If zk When using cluster deployment , Refer to the following for configuration writing :

<dubbo:registry address="zookeeper://172.28.*.102:2181?backup=172.28.*.102:2182,172.28.*.102:2183"/>

 

dubbo There's also a management interface , For service governance , Includes enabling / Disable Service , Set the routing rules of the service ( namely :A Address of the Consumer Call directly B Mechanical Provider, Instead of being distributed by a load balancing algorithm ) wait .

Usage method : take dubbo-admin This project is compiled into war After package , Deploy to jetty Or other compatible web server that will do ( Of course, it needs to be modified \WEB-INF\dubbo.properties in zk The address of )

After deployment , When accessing the management interface , Default user name , All passwords are root. 

in addition dubbo-monitor The project is used for performance monitoring , Combined with the data generated by monitoring , Then put on some charts to show the framework , Various indicators can be visually displayed in the form of charts .

notes : From the official website dubbo-admin Adopted webx The architecture is a little old , And besides Taobao , Few people are using ,dubbo-monitor-simple The interface is also quite simple , So the community has also expanded it , For details, please refer to another blog dubbox All kinds of management and supervision

2016-02-25:dubbox Rely on the spring Although upgraded to 3.x 了 , But the version is still a little low ,spring Have been 4.x 了 , For my convenience fork A copy of , Upgrade to spring 4.x At the same time, it added log4j2 The log component supports , For details, see :dubbox upgrade spring To 4.x And add log4j2 Support

 

 

版权声明
本文为[mb60f93b6c4c5e3]所创,转载请带上原文链接,感谢
https://javamana.com/2021/07/20210723181502197i.html

  1. redis 监控的一些构思
  2. Some ideas of redis monitoring
  3. Spring中获取request的几种方法,及其线程安全性分析
  4. Several methods of getting request in spring and its thread security analysis
  5. 20分钟带你掌握JavaScript Promise和 Async/Await
  6. 20 minutes with async and async
  7. Mybatis - introduction, simple entry program
  8. Java Concurrent Programming: concurrent HashMap
  9. Mybatis: one to one association query
  10. Java IO
  11. Object oriented [day07]: review of knowledge points (11)
  12. Chapter 2 spring
  13. Process of building minicube in local k8s environment
  14. Interpretation of jQuery source code
  15. Making web full screen effect with jquery
  16. Java 7 exception handling new features - address suppressed () method
  17. Spring 4 uses websocket
  18. Using openldap to answer questions and using java to complete LDAP authentication
  19. Implementation of MySQL high availability cluster with corosync + pacemaker and DRBD
  20. Java production of a simple tank war
  21. Design pattern day02
  22. Hadoop pseudo Distributed installation and running test example
  23. Java Concurrent Programming: callable, future and futuretask
  24. Understanding the three characteristics of Java encapsulation
  25. Understanding closure of JavaScript
  26. Java set excel worksheet to read only
  27. Distributed Java service platform baratine
  28. Java barcode generation technology barcode4j
  29. Use springboot + MySQL + JPA to add, delete, change, query and page the database
  30. Zookeeper notes (1) installation, deployment and hello world
  31. Oracle database trigger Usage Summary
  32. MySQL master replication with slave server