1.添加JavaBean配置
项目中添加如下JavaBean配置就可以使用RestTemplate负载均衡调用了
@LoadBalanced 此注解开启负载均衡,Ribbon默认使用的是轮询算法
@Configurationpublic class ApplicationContextConfig {@Bean@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();}}
2.Api示例
restTemplate.getForEntity方法:返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头,响应状态码,响应体等。
restTemplate.getForObject方法:返回对象为响应体中数据转化成的对象,基本上可以理解为JSON
@GetMapping("/consumer/payment/getForEntity/{id}")public CommonResult<Payment> getForEntity(@PathVariable("id") Long id) {ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);if (entity.getStatusCode().is2xxSuccessful()) {log.info(entity.getStatusCode() + "\t" + entity.getHeaders());return entity.getBody();} else {return new CommonResult<>(444, "操作失败");}}@GetMapping("/consumer/payment/create")public CommonResult<Payment> create(Payment payment) {CommonResult commonResult = restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);return commonResult}
