dtef9322 2013-06-03 16:15
浏览 68
已采纳

PHP curl_init负载均衡多个服务器

I've got a service that is calling a REST server. I'm using CURL to make the request. We have three endpoints to use for distributing the load. I could create some basic logic that would "randomly" pick an end point but that doesn't seem like a "good" solution. I'm wondering if there is a better solution?

define ("REST_SERVER", "http://myService.myCompany.com:8280");
...
$url = REST_SERVER.URL_SIGN;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json',
  'Content-Length: ' . strlen($data_string))
);
$curl_result = curl_exec($ch);
  • 写回答

1条回答 默认 最新

  • dqppv86022 2013-06-03 17:05
    关注

    If you're looking for a poor-man's load balancer, you'd enumerate your endpoints into an array, call shuffle() and array_pop() the lucky winner.

    <?php
    $endpoints = array(
       'http://api1.myco.com',
       'http://api2.myco.com'
    );
    
    shuffle($endpoints);
    
    define('REST_SERVER', array_pop($endpoints));
    
    // ...
    ?>
    

    I'd also suggest you vet each candidate to ensure it's "up"/"available" before issuing API calls, which is outside the context of this question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?