1. 程式人生 > >Spring Cloud學習(二)Ribbon簡單使用

Spring Cloud學習(二)Ribbon簡單使用

Ribbon簡介

Ribbon是一個負載均衡客戶端,可以很好的控制http和tcp的一些行為。Feign預設集成了Ribbon。

示例:

@SpringBootApplication
@EnableDiscoveryClient  //向服務中心註冊
public class RibbonApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder(RibbonApplication.class).web(true).run(args);
    }

    @Bean
    @LoadBalanced //開啟負載均衡的功能
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
@RestController
public class HelloControler {

    @Autowired
    HelloService helloService;

    @RequestMapping(value = "/hi")
    public Integer hi(){
        return helloService.hiService();
    }
}
@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    public Integer hiService() {
        return restTemplate.getForObject("http://COMPUTE-SERVICE/add?a=" + 1 + "&b=2", Integer.class);
    }
}

通過呼叫restTemplate.getForObject(“http:// COMPUTE-SERVICE/…)方法時,restTemplate會做負載均衡,把請求路由到註冊在註冊中心的服務提供者機器上去,完成服務呼叫。