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.
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.
For complete example source code, please refer to dubbo-samples-stub
<dubbo:consumer interface="com.foo.BarService" stub="true" />
or
<dubbo:consumer interface="com.foo.BarService" stub="com.foo.BarServiceStub" />
package com.foo;
public class BarServiceStub implements BarService {
private final BarService barService;
// Constructor takes in the real remote proxy object
public BarServiceStub(BarService barService){
this.barService = barService;
}
public String sayHello(String name) {
// This code runs on the client; you can create ThreadLocal local caches or validate parameters
try {
return barService.sayHello(name);
} catch (Exception e) {
// You can provide fault tolerance; perform any AOP interception here
return "Fault tolerance data";
}
}
}