vertx single webClient connect to multiple servers

2019-03-06 21:58发布

问题:

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.