vertx single webClient connect to multiple servers cluster for load balance and avoid connectivity fails

左心房为你撑大大i 提交于 2019-12-02 18:09:45

问题


We connect to a server fts.server using a web client using the below method .

webClient.post(config.getInteger("fts.port"), config.getString("fts.server"), config.getString("fts.indexpath")).putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic " + base64key).sendJsonObject(jreq, ar -> {
                    if (ar.succeeded()) {
            }
            else 
            { 
            }
} 

In my case i have fts.server1 , fts.server2 , fts.server3 all providing the same service . I need to load balance the calls between the servers and if any of them are off line try the other server . Some thing like

webClient.post(config.getInteger("fts.port"), (config.getString("fts.server1")) or config.getString("fts.server2")) or config.getString("fts.server3"))   , config.getString("fts.indexpath")).putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic " + base64key).sendJsonObject(jreq, ar -> {
                    if (ar.succeeded()) {
            }
            else 
            { 
            }
}

How do i do it ?


回答1:


First, there are loadbalancers, specifically for that.

But to the point at hand. Instead of having one client and trying to loadbalance it, create N clients, and loadbalance between them.

Using Java9:

var list = List.of(WebClient.create(vertx, new WebClientOptions().setDefaultHost("fts1")),
                WebClient.create(vertx, new WebClientOptions().setDefaultHost("fts2")),
                WebClient.create(vertx, new WebClientOptions().setDefaultHost("fts3")));

Now it's up to you to decide how do you loadbalance between them.

Random?

Random r = new Random();
WebClient c = list.get(r.nextInt(list.size()));

Round robin?

AtomicInteger count = new AtomicInteger();
WebClient c = list.get(count.getAndIncrement() % list.size());

That's up to you.



来源:https://stackoverflow.com/questions/54797101/vertx-single-webclient-connect-to-multiple-servers-cluster-for-load-balance-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!