1.Ribbon和Nginx區別
Nginx服務器負載均衡: 客戶端所有請求都會交給nginx,然后由nginx實現轉發請求,即負載均衡是由服務端實現。nginx服務負載均衡適合於針對服務器端,比如:tomcat、jetty等
Ribbon本地負載均衡 :在調用接口的時候、會在eureka注冊中心上獲取注冊信息服務列表,獲取到之后,緩存在jvm本地,使用本地實現rpc遠程技術進行調用,即是客戶端實現負載均衡。ribbon本地負載均衡適合微服務rpc遠程調用,比如:dubbo,springcloud等
2.負載均衡之實現
控制器中測試代碼:
@Controller
public class TestController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value ="/test",method = RequestMethod.GET)
@ResponseBody
public Object test() {
//根據服務端注冊的服務,調用相應方法
return restTemplate.getForEntity("http://eurekaClient/testEureka",String.class).getBody();
}
}
在配置類中添加以下代碼
@Bean
@LoadBalanced//輪詢方式
public RestTemplate restTemplate(){
return new RestTemplate();
}