Local Stub

Understand the use of local stubs executing part of the logic on the client side in Dubbo

Feature Description:

After invoking a remote service, the client typically only has the interface, while the implementation resides entirely on the server. However, sometimes the provider wants to execute part of the logic on the client side as well.

/user-guide/images/stub.jpg

Usage Scenarios

For scenarios such as creating ThreadLocal caches, validating parameters in advance, or simulating fault tolerance data after a failed call, the API needs to have a Stub. The client generates a Proxy instance, which is passed to the Stub through the constructor 1, and then the Stub is exposed to the user. The Stub can decide whether to invoke the Proxy.

Usage Method

For complete example source code, please refer to dubbo-samples-stub

Spring Configuration File

  1. <dubbo:consumer interface="com.foo.BarService" stub="true" />

or

  1. <dubbo:consumer interface="com.foo.BarService" stub="com.foo.BarServiceStub" />

Providing Stub Implementation 2

  1. package com.foo;
  2. public class BarServiceStub implements BarService {
  3. private final BarService barService;
  4. // Constructor takes in the real remote proxy object
  5. public BarServiceStub(BarService barService){
  6. this.barService = barService;
  7. }
  8. public String sayHello(String name) {
  9. // This code runs on the client; you can create ThreadLocal local caches or validate parameters
  10. try {
  11. return barService.sayHello(name);
  12. } catch (Exception e) {
  13. // You can provide fault tolerance; perform any AOP interception here
  14. return "Fault tolerance data";
  15. }
  16. }
  17. }

  1. The Stub must have a constructor that accepts a Proxy. ↩︎

  2. Place a Stub implementation next to the interface that implements the BarService interface and has a constructor that accepts the remote BarService instance. ↩︎

Feedback

Was this page helpful?

Yes No

Last modified September 30, 2024: Update & Translate Overview Docs (#3040) (d37ebceaea7)