Dubbo Some Useful Functions You Don’t Know

Source: Internet
Author: User
Keywords apache dubbo direct provider echo testing implicit parameter
The function of dubbo is very complete. Many times we don't need to reinvent the wheel. Here are some functions that you may not know, but are very useful.

Direct Provider
In the development and test environment, it may be necessary to bypass the registry and only test the designated service provider. At this time, it may require a point-to-point direct connection. The point-to-point direct connection mode will be based on the service interface and ignore the provider list of the registry. A The interface configuration is point-to-point, and does not affect the B interface to obtain the list from the registry (Note: the official only recommends the development & test environment to use this function), the usage is as follows, the address specified by the url is the direct connection address:
<dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" version="1.0.0" url="dubbo://172.18.1.205:20888/" />

Multi-version
When an interface is implemented and there is an incompatible upgrade, you can use the version number to transition. Services with different version numbers do not reference each other. The usage is as follows:
<dubbo:service interface="com.alibaba.dubbo.demo.DemoService" ref="demoService" version="1.0.0" />

Using this feature of dubbo, we can achieve gray release of some functions, the implementation steps are as follows:

The old implementation definition of the interface version="1.0.0", the new implementation of the interface version="2.0.0"
Consumer end definition version="*"
After defining Provider and Consumer in this way, the old and new interfaces will each bear 50% of the traffic;

With this feature of dubbo, incompatible version migration can also be completed:

During the low pressure period, first upgrade half of the Provider to the new version;
Then upgrade all consumers to the new version;
Then upgrade the remaining half of the providers to the new version.


Echo test

The echo test is used to detect whether the service is available. The echo test is executed in accordance with the normal request process, can test whether the entire call is smooth, and can be used for monitoring.
All services automatically implement the EchoService interface, and only need to force any service reference to EchoService to be used, the usage method (demoService is a bean managed by spring)
EchoService echoService = (EchoService) demoService;
System.out.println(echoService.$echo("hello"));

Implicit parameter
You can use RpcContext's setAttachment() and getAttachment() to implicitly transfer parameters between Consumer and Provider. For example, the Controller layer intercepts the login token, and passes the memberId obtained from the token to the dubbo service to use implicit parameter transfer. The KV pair set by setAttachment() will be cleared after one remote call is completed, that is, multiple remote calls must be set multiple times. How to use:

1. Server set:
RpcContext.getContext().setAttachment("CRT_MEMBER_ID", "13828886888");

2. Client get:
RpcContext.getContext().getAttachment("CRT_MEMBER_ID")

Context
What is stored in the context is the environment information needed during the current call. All configuration information will be converted to URL parameters
RpcContext is a ThreadLocal temporary status recorder. When an RPC request is received or an RPC request is initiated, the status of the RpcContext
Will change. For example: A is adjusted to B, then B is adjusted to C, then on machine B, before B is adjusted to C, RpcContext records the information of A to B, in B to C
After that, RpcContext records the information of B to C. How to use:
boolean isConsumerSide = RpcContext.getContext().isConsumerSide();

Local camouflage
Local camouflage is usually used for service degradation, such as a certain authorization service. When the service provider hangs up, the client does not throw an exception, but uses mock data
Return authorization failed. The usage is as follows, the implementation class specified by mock is executed when the Provider throws RpcException (it must be executed only after the RpcException is thrown), instead of returning the result remotely:
<dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" version="1.0.0" mock="com.alibaba.dubbo.demo.consumer.mock.DemoServiceMock"/>

DemoServiceMock implementation source code:
public class DemoServiceMock implements DemoService {
    public String sayHello(String name) {
        return "mock-value";
    }
}
Generalized call
The generalized interface call method is mainly used when the client does not have an API interface and model class element. All POJOs in the parameters and return values are represented by Map, which is usually used for framework integration. For example, to implement a general service testing framework, Call all service implementations through GenericService. How to use:
<dubbo:reference id="demoService" interface="com.alibaba.dubbo.demo.DemoService" generic="true"/>

 Call source code:
/**
 * @author afei
 * @version 1.0.0
 * @since November 22, 2017
 */
public class Main {
 
    public static void main(String[] args) {
        // Quote the remote service, this instance encapsulates all connections to the registration center and service provider, please cache
        ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
        // Weak type access name
        reference.setInterface("com.alibaba.dubbo.demo.DemoService");
        reference.setVersion("1.0.0");
        // Declared as a generalized interface
        reference.setGeneric(true);
        // Use com.alibaba.dubbo.rpc.service.GenericService to replace all interface references
        GenericService genericService = reference.get();
        // Basic types and Date, List, Map, etc. do not need to be converted, directly call
        Object result = genericService.$invoke("sayYes", new String[] {"java.lang.String"}, new Object[] {"afei"});
        System.out.println("result --> "+result);
 
        // Use Map to represent POJO parameters, if the return value is POJO, it will automatically be converted to Map
        Map<String, Object> teacher = new HashMap<String, Object>();
        teacher.put("id", "1");
        teacher.put("name", "admin");
        teacher.put("age", "18");
        teacher.put("level", "3");
        teacher.put("remark", "test");
        // If it returns POJO, it will be automatically converted to Map
        result = genericService.$invoke("justTest", new String[]
                {"com.alibaba.dubbo.demo.bean.HighTeacher"}, new Object[]{teacher});
        System.out.println("result --> "+result);
    }
}


Access log
If you want to record the information of each request, you can open the access log, similar to the Ngnix access log. Note: This log volume is relatively large, please pay attention to the disk capacity. How to use (if local is configured, the global access log will be invalid):
Configure global:
<dubbo:provider accesslog="/app/dubbo-demo.log"/>
Configuration part:
<dubbo:service interface="com.alibaba.dubbo.demo.DemoService" ref="demoService" accesslog="/app/demo.log"/>
 
 <dubbo:service interface="com.alibaba.dubbo.demo.TestService" ref="testService" accesslog="/app/test.log"/>

Log format style:
[2017-11-22 10:23:20] 172.18.1.205:56144 -> 172.18.1.205:20886-com.alibaba.dubbo.demo.DemoService:1.0.0 sayHello(java.lang.String) ["afei" ]

Delayed exposure
If the service requires warm-up time, such as initializing the local cache, waiting for related resources to be in place, etc., you can use delay for delayed exposure. Make Dubbo delay how many milliseconds after the Spring container is initialized before exposing the service. How to use:
<dubbo:provider delay="5000"/>
or:
<dubbo:service delay="5000" interface="com.alibaba.dubbo.demo.DemoService" ref="demoService" version="1.0.0"/>

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.