Generic Implementation

Generic implementation for providing and publishing services when the provider does not have an API (SDK)

The generic interface implementation method is mainly used in scenarios where the server side does not have API interfaces and model class metadata. All POJOs in parameters and return values are represented using Map, usually for framework integration. For example, to implement a generic remote service Mock framework, you can handle all service requests by implementing the GenericService interface.

Use Cases

  • Service Registration: The service provider registers services in the service registry, such as Zookeeper, which stores information about the service, such as its interfaces, implementation classes, and addresses.

  • Service Deployment: The service provider deploys the service on a server and makes it available to consumers.

  • Service Invocation: Users call services generated by the service registry proxy, forwarding requests to the service provider, which executes the service and sends responses back to the consumer.

  • Service Monitoring: Providers and consumers can use the Dubbo framework to monitor services, allowing them to view service execution and make adjustments as needed.

Usage

Refer to the complete source code for this example at dubbo-samples-generic-impl.

Implement the GenericService interface in Java code

package com.foo;
public class MyGenericService implements GenericService {

    public Object $invoke(String methodName, String[] parameterTypes, Object[] args) throws GenericException {
        if ("sayHello".equals(methodName)) {
            return "Welcome " + args[0];
        }
    }
}

Exposing Generic Implementation through Spring

Declare the service implementation in Spring XML configuration

<bean id="genericService" class="com.foo.MyGenericService" />
<dubbo:service interface="com.foo.BarService" ref="genericService" />

Exposing Generic Implementation through API

...
// Use org.apache.dubbo.rpc.service.GenericService instead of all interface implementations
GenericService xxxService = new XxxGenericService();

// This instance is heavyweight, encapsulating all connections to the registry and service provider; please cache it
ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
// Weak type interface name
service.setInterface("com.xxx.XxxService");
// If you need to set a different version for the service
service.setVersion("1.0.0");
// Point to a generic service implementation
service.setRef(xxxService);

// Expose and register the service
service.export();
  1. When setting ServiceConfig, use setGeneric("true") to enable generic invocation
  2. When setting ServiceConfig, use setRef to specify the implementation class, and set an object of GenericService, not the actual service implementation class object
  3. Other settings are consistent with normal API service starts
Last modified September 30, 2024: Translate (22d3d83a3b)