Developing restful remote calls in Dubbo (restful Remoting)

Source: Internet
Author: User
Tags format message http post json regular expression serialization web services port number ibm developerworks

http://zyg345646335.iteye.com/blog/2208899

Catalog Overview Rest Benefits Scenario QuickStart Standard Java Rest api:jax-rs Introduction Rest service provides a study of the implementation of the HTTP Post/get annotation in the interface class or implementation of the class JSON, XML and other multi-data grid Supports additional requirements for XML data formats custom serialization configuration Rest server Implementation Get context information Configure Port number and Context Path Configure the number of threads and number of IO threads Configure the maximum number of HTTP connections configured for a long connection configuration per consumer The timeout period and the number of HTTP connections gzip data compression with annotation replace partial spring XML configuration Add custom filter, interceptor etc. add custom exception processing configure HTTP log output input parameter checksum Should I transparently publish rest service Rest Service Consumption Review Scenario 1: Non-Dubbo consumer calls Dubbo Rest service scenario 2:dubbo consumer calls Dubbo Rest service scenario 3:dubbo consumer calls non-Dubbo rest service Dubbo Jax-rs's Limited rest FAQ (Rest FAQ) Dubbo Rest Services can be integrated with Dubbo registry, monitoring Center. How to implement load balancing and fault tolerance (failover) in Dubbo rest. The overloaded methods in Jax-rs can be mapped to the same URL address. The method of post in Jax-rs can receive multiple parameters. Dubbo possible deficiencies of the current system (rest-related)
Limitations of Rpccontext's intrusive protocol configuration XML naming does not conform to spring specification rest best practices Performance benchmarks
Test environment test Script test Results extension discuss rest vs. Thrift, protobuf, and more compare rest to traditional webservices jax-rs vs. spring MVC future Overview

Dubbo supports multiple remote invocation methods, such as Dubbo RPC (binary serialization + TCP protocol), HTTP invoker (binary serialization + HTTP protocol, no support for text serialization found at least in open source versions), Hessian (binary serialization + HTTP protocol) , WebServices (text serialization + HTTP protocol), etc., but lacks support for today's particularly popular restful remote invocation (text serialization + HTTP protocol).

In view of this, our standard-based Java Rest Api--jax-rs 2.0 (Java API for RESTful Web Services shorthand) provides close-to-transparent REST invocation support for Dubbo. Due to the full compatibility of the Java Standard API, all rest services developed for Dubbo will normally run in the future out of Dubbo or any particular rest underlying implementation.

It is particularly noteworthy that we do not need to strictly abide by the original definition and architectural style of rest. Even the well-known Twitter rest API adjusts appropriately to the situation, rather than mechanically adhering to the original rest style.

Note: We call this feature a restful remote call, that is, restful Remoting (abstract remoting or invocation), rather than restful RPC (a specific remote "procedure" call), because rest and RPC itself can be thought of as two different styles. In Dubbo's rest implementation, there are two aspects, one is to provide or consume a normal rest service, and the other is to implement rest as a protocol in the Dubbo RPC architecture, while the restful remoting covers this aspect. Benefits of Rest

The following excerpt from Wikipedia: More efficient use of caching to improve response speed the stateless nature of the communication itself allows different servers to process different requests in a series of requests, increasing the server's extensibility browser as a client, simplifying the software requirements relative to other mechanisms superimposed on the HTTP protocol, Rest is less software-dependent and requires no additional resource discovery mechanisms for long-term compatibility in software technology evolution better

Here I would also like to add a special benefit to rest: It is based on a simple text format message and a common HTTP protocol, making it highly adaptable, supported by almost all languages and platforms, and with a lower threshold for learning and using. Application Scenarios

Thanks to the benefits of rest in terms of applicability, rest is supported in Dubbo, which brings (significant) benefits to most mainstream remote invocation scenarios today:

Significantly simplifies (cross-language) calls between heterogeneous systems within the enterprise. This is mainly for this scenario: The Dubbo system serves as a service provider, and other language systems (including some Java systems that are not based on Dubbo) do the service consumption, and both communicate via HTTP and text messages. Rest has its own unique advantages even when compared to thrift, protobuf, and other binary cross-language invocation scenarios (see discussion later)

Significantly simplifies the development of external open APIs (open platforms). You can either use Dubbo to develop a dedicated open API application, or you can publish the original internal use of the Dubbo service directly "transparent" to external open REST API (of course, the future of Dubbo itself is best to provide more transparent such as permission control, frequency control, Billing, and many other functions)

Significantly simplifies mobile (tablet) app or PC desktop client development. Similar to 2, you can use the Dubbo to develop a server-side specifically for wireless or desktop, or the original internal use of the Dubbo service directly "Transparent" to the mobile app or desktop programs. Of course, in some projects, the mobile phone or desktop program can also directly access the open API described in Scenario 2 above.

Significantly simplifies the development of browser AJAX applications. Similar to 2, you can use Dubbo to develop a dedicated AJAX server side, or the original internal use of the Dubbo service directly "Transparent" exposure to JavaScript in the browser. Of course, many AJAX applications are better suited to work with web frameworks, so direct access to the Dubbo service is not necessarily a very elegant architecture in many Web projects.

Provides a text-based, easy-to-read, remote invocation method between Dubbo systems within the enterprise (i.e., service provider and consumer are based on Dubbo systems).

To some extent simplifies the invocation of Dubbo systems to other heterogeneous systems. The rest services provided by non-Dubbo systems can be "transparently" invoked in a simple way similar to Dubbo (whether the service provider is internal or external)

It should be noted that I think that Dubbo is the most valuable three scenarios for rest invocation, and we add rest calls for Dubbo, whose primary to purpose is the service-oriented provider, which is to develop rest services to provide to non-Dubbo (heterogeneous) consumers.

To sum up, all the scenarios are shown in the following figure:

By borrowing Java's most popular propaganda words, adding rest calls to Dubbo, you can implement the service "write once, visit everywhere", and theoretically open up to the world, to truly achieve a more idealized service-oriented architecture (SOA).

Of course, the traditional webservices (Wsdl/soap) also basically satisfies the requirements of the above scenario (except Scenario 4) (even those that require enterprise-class features), but because of its complexity, there are fewer and less practical uses. Quick Start

It is easier to develop a restful service in Dubbo, as illustrated by an example of a registered user's simple service.

The function to be implemented by this service is to provide the following URL (note: This URL is not completely restful in style, but simpler and more practical):

Http://localhost:8080/users/register

Any client can post a JSON string containing user information to the above URL to complete the user registration.

First, the interface for the development service:

public class UserService {    
   void RegisterUser (user user);
}

Then, the implementation of the development service:

@Path ("Users") public
class Userserviceimpl implements UserService {

    @POST
    @Path ("register")
    @ Consumes ({Mediatype.application_json}) public
    void RegisterUser (user user) {
        //Save the user ...
    }
}

The service implementation code above is very simple, but since the rest service is to be published to a specific HTTP URL for any language client or even a browser to access, there are several additional Jax-rs standard annotation to do the relevant configuration:

@Path ("Users"): Specifies that the URL relative to the access UserService is/users, which is http://localhost:8080/users

@Path ("register"): Specifies that the URL relative path to the RegisterUser () method is/register, combined with the path specified by the previous @Path for UserService, calls Userservice.register ( ) The full path is Http://localhost:8080/users/register

@POST: Specify Access RegisterUser () with the HTTP POST method

@Consumes ({Mediatype.application_json}): Specifies that RegisterUser () receives JSON-formatted data. The rest framework automatically deserializes JSON data into a user object

Finally, add this service in the spring configuration file to complete all service development work:

<!--with rest protocol on 8080 port exposure service
--<dubbo:protocol name= "rest" port= "8080"/>

<!--declares the service interface that needs to be exposed--
<dubbo:service interface= "xxx. UserService "ref=" UserService "/>

<!--and local beans are implemented as service
--<bean id=" userservice "class=" xxx. Userserviceimpl "/>
Introduction to standard Java REST api:jax-rs

Jax-rs is a standard Java REST API that has been widely supported and used by the industry, with many notable open source implementations, including Oracle's Jersey,redhat Resteasy,apache cxf and Wink, and Restlet, among others. In addition, JAX-RS is supported by all commercially available Java EE application servers that support Java EE 6.0 specifications. Therefore, Jax-rs is a very mature solution, and it does not have any so-called vendor lock-in problems.

Jax-rs is very informative on the web, such as the following introductory tutorial: Oracle's official tutorial:http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs.htm IBM Developerworks China Station article: http://www.ibm.com/developerworks/cn/java/j-lo-jaxrs/

More information please google or Baidu a bit. As far as learning Jax-rs is concerned, it is generally important to master the usage of various annotation.

Note: Dubbo is based on the Jax-rs 2.0 version, and sometimes you need to be aware of the version involved in the data or rest implementation. Rest Service provides a solution

Below we expand the userservice in the QuickStart to further demonstrate the development essentials of the rest service provider in Dubbo. implementation of HTTP Post/get

While the rest service is recommended to use four standard methods of the HTTP protocol post, DELETE, PUT, get to implement the common "Add and remove changes", but in practice, we generally directly use post to achieve "change", get to achieve "censored" (delete and put are even blocked by some firewalls).

The previous implementation of the post has been briefly demonstrated, where we add a function to get the registered user profile for UserService to demonstrate the get implementation.

This function is to enable the client to access the following different URLs to obtain different ID user profile:

http://localhost:8080/users/1001
http://localhost:8080/users/1002
http://localhost:8080/users/1003

Of course, other forms of URLs can also be used to access different IDs of user data, such as:

http://localhost:8080/users/load?id=1001

Jax-rs itself can support all these forms. But the type of the above that contains query parameters in the URL path (http://localhost:8080/users/1001) is more in line with rest's general habits, so it is recommended to use them. Let's add a GetUser () method for UserService to implement this form of URL access:

@GET
@Path ("{ID: \\d+}")
@Produces ({Mediatype.application_json}) public
User GetUser (@PathParam ("id") Long ID) {
    //...
}

@GET: Specifies access using the HTTP GET method

@Path ("{ID: \d+}"): The URL to access GetUser () should be "http://localhost:8080/users/+ any number" according to the functional requirements above, and this number will be passed as a parameter to the GetUser () method. Here in the annotation configuration, the {id:xxx} in the middle of the @Path specifies that the URL relative to the path contains the name ID parameter, and its value is automatically passed to the following method parameter ID, decorated with @pathparam ("id"). {ID: The immediately following \d+ is a regular expression that specifies that the ID parameter must be a number.

@Produces ({Mediatype.application_json}): Specifies GetUser () output JSON-formatted data. The framework automatically serializes the user object into JSON data. annotation on the interface class or implementation class

The rest services developed in Dubbo are mostly configured through the Jax-rs annotation, and in the example above, we put annotation in the implementation class of the service. But in fact, we can also put annotation on the interface of the service, these two methods are completely equivalent, for example:

@Path ("Users")

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.