Custom LoadBalancer
For a reference implementation of a custom registry center class, see com.alipay.sofa.rpc.client.lb.RandomLoadBalancer.
The process for customizing a load balancer is as follows:
Implement a custom load balancer
You can create a custom load balancer class.
Create a custom load balancer class that inherits the following abstract class:
package com.alipay.sofa.rpc.client; public abstract class AbstractLoadBalancer extends LoadBalancer { protected abstract ProviderInfo doSelect(SofaRequest invocation, List<ProviderInfo> providerInfos); // Performs load balancing. }Add an annotation.
Example:
@Extension("shortestResponse") public class ShortestResponseLoadBalance extends AbstractLoadBalancer {Use the
@Extension("")annotation to specify a custom alias for the load balancer. You can use this alias when you specify the load balancing algorithm for your service.
Configure the custom load balancer in the RPC framework
SOFARPC uses a Service Provider Interface (SPI) mechanism. To configure your custom load balancer class in the RPC framework, create an extension file named com.alipay.sofa.rpc.client.LoadBalancer in the META-INF/services/sofa-rpc/ directory. The following example shows the file content:
shortestResponse=com.alipay.sofa.extend.loadbalance.ShortestResponseLoadBalance
Use the custom load balancer in your service
When you specify a load balancing algorithm, use the alias of your custom load balancer. For more information about load balancing algorithms and configurations, see Load balancing.
The following example shows a sample configuration:
<sofa:reference interface="com.example.demo.SampleService" id="sampleService">
<sofa:binding.bolt>
<sofa:global-attrs loadBalancer="shortestResponse"/>
</sofa:binding.bolt>
</sofa:reference>