GRPC负载均衡器示例

4
我正在尝试使用GRPC/Java构建具有负载均衡的服务器集管理机制。通过查看API文档,有类如LoadBalancer、RoundRobinLoadBalancerFactory等。从名称上看,它们似乎应该做我想做的事情。然而,即使我非常努力地搜索,也找不到使用这些类的任何代码示例。另一方面,我发现了一些Finagle/Thrift示例,例如:https://github.com/benjumanji/finagle-serverset-example。我想知道是否有人可以分享一些工作的GRPC示例?谢谢!
3个回答

4

gRPC的负载均衡器名称解析器配合使用。名称解析器向负载均衡器发出地址,负载均衡器决定建立连接(Subchannels)并为每个请求选择子通道

可以将名称解析器和/或负载均衡器设置为ManagedChannelBuilder,以用于通道。

虽然有接口,但是没有太多的默认实现,而只有基本的DnsNameResolver和RoundRobinLoadBalancer。PickFirstBalancerFactory是默认的“负载均衡器”,实际上不进行平衡。

如果您的地址在DNS中有多个地址,则在使用RoundRobinLoadBalancer时会观察到轮询行为。但是,我猜您想从ZooKeeper等服务发现系统中获取地址。您需要为此实现一个名称解析器。如果您熟悉所选的发现系统,则不应该很难。


0

我刚在Kidong Lee的Github存储库中找到了一个Java版本的示例: https://github.com/mykidong/grpc-java-load-balancer-using-consul/blob/master/src/test/java/io/shunters/grpc/component/grpc/HelloWorldClientWithNameResolver.java

/**
 * Consul NameResolver Usage.
 *
 *
 * @param serviceName consul service name.
 * @param consulHost consul agent host.
 * @param consulPort consul agent port.
 * @param ignoreConsul if true, consul is not used. instead, the static node list will be used.
 * @param hostPorts the static node list, for instance, Arrays.asList("host1:port1", "host2:port2")
 */
public HelloWorldClientWithNameResolver(String serviceName,
                                        String consulHost,
                                        int consulPort,
                                        boolean ignoreConsul,
                                        List<String> hostPorts) {

    String consulAddr = "consul://" + consulHost + ":" + consulPort;

    int pauseInSeconds = 5;

    channel = ManagedChannelBuilder
            .forTarget(consulAddr)
            .loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
            .nameResolverFactory(new ConsulNameResolver.ConsulNameResolverProvider(serviceName, pauseInSeconds, ignoreConsul, hostPorts))
            .usePlaintext(true)
            .build();

    blockingStub = GreeterGrpc.newBlockingStub(channel);
}

你可以在这个代码库中找到更多的例子。


-1

我们刚刚发布了一个非常简单的示例,可以在这里找到:https://github.com/cloudtrust/lbclient/blob/master/grpc/staticResolver.go

package grpc

import (
"google.golang.org/grpc/naming"
)

type staticResolver struct{
    updates []*naming.Update
}

type staticWatcher struct {
    updates chan []*naming.Update
}

func NewStaticResolver(addr []string) naming.Resolver {
    var ups []*naming.Update
    for _,a := range addr {
        ups = append(ups, &naming.Update{naming.Add, a, ""})
    }
    return &staticResolver{ups}
}

func (w *staticWatcher) Next() ([]*naming.Update, error) {
    return <-w.updates, nil
}

func (w *staticWatcher) Close() {
    close(w.updates)
}

func (r *staticResolver) Resolve(target string) (naming.Watcher, error) {
    var ch chan []*naming.Update = make(chan []*naming.Update, 1)
    ch <- r.updates
    return &staticWatcher{ch}, nil
}

希望这能对你有所帮助,如果你需要任何帮助,请随时提问。


非常感谢!你有Java版本的示例吗? - Alfred Zhong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接