Home > OS >  Api Rest 3 servers
Api Rest 3 servers

Time:10-25

I have 3 servers, server one is always the first server to be "called". this is the code i have:

Future<String> verifyAllProd() async {
  var conf = Configuracoes.auth;
  var url = Uri.parse(
      'http://adsa.er.net:81/APP1/APPProducts');
  http.Response response = await http.get(
    url,
    headers: {
      HttpHeaders.authorizationHeader: conf,
    },
  );
  if (response.statusCode != 200) {
    response = await http.get(
      Uri.parse(
          'http://adsa.er.net:82/APP1/APPProducts'),
      headers: {
        HttpHeaders.authorizationHeader: conf,
      },
    );
  }
  if (response.statusCode != 200) {
    response = await http.get(
      Uri.parse(
          'http://adsa.er.net:83/APP1/APPProducts'),
      headers: {
        HttpHeaders.authorizationHeader: conf,
      },
    );
  }
  if (response.statusCode == 200) {
    return response.body;
  }
  throw Exception(response.reasonPhrase);
}


Supposedly with this code, when the server one sent a response other than 200 it passed to the "if", I think it is working correctly.

But now when server 1 is off the call is made and it is infinitely waiting for the answer.

So I wanted that after 2 seconds, if I didn't hear an answer, it would go the next server

CodePudding user response:

Set a timeout on your get call and implement the onTimeout:

 await http
  .get(
    url,
  )
  .timeout(const Duration(seconds: 1),
      onTimeout: () => http.Response('Timeout', 408));

CodePudding user response:

While you could deal with this at the client, it's much more common to put your 3 servers behind a load balancer (with health-checking).

  • Related