使用RestTemplate調用SpringCloud注冊中心內的服務
本案例使用Eureka作為注冊中心演示,其他注冊中心調用方式一致。只需保證調用方和服務提供方必須在同一個注冊中心內注冊即可。
啟動類上加入注解
這里演示的是Eureka的形式,其他的注冊中心根據實際情況添加即可。EnableEurekaClient其實也是可以不用加的。
@SpringBootApplication
@EnableEurekaClient
配置RestTemplate
在SpringBoot啟動類所在包的同級或子包內加入如下配置,如果調用的服務不是唯一的,必須加上@LoadBalanced
注解
package cn.vantee.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author :rayfoo@qq.com
* @date :Created in 2021/12/25 4:28 下午
* @description:RestTemplatep配置類
* @modified By:
* @version: 1.0.0
*/
@Configuration
public class ApplicationContextConfig {
/**
* 如果是集群方式調用需要加上LoadBalanced 否則會502
* @return
*/
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
使用RestTemplate調用服務
resttemplate不僅支持ip+端口的形式調用接口,還支持根據調用服務注冊中心中的應用名稱調用。
package cn.vantee.proxy;
import cn.vantee.entity.AjaxResult;
import cn.vantee.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author :rayfoo@qq.com
* @date :Created in 2021/12/25 4:28 下午
* @description:訂單模塊的控制層
* @modified By:
* @version: 1.0.0
*/
@RestController
@RequestMapping("/order")
public class OrderProxy {
/**
* 支付服務的地址,支持ip+端口和服務名
*/
public static final String PAYENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Autowired
private RestTemplate restTemplate;
/**
* 通過RestTemplate遠程調用支付服務
* @param id
* @return
*/
@GetMapping("/payment/findOne/{id}")
public AjaxResult<Payment> findPaymentById(@PathVariable("id") long id) {
return restTemplate.getForObject(PAYENT_URL+"/payment/findOne/"+id,AjaxResult.class);
}
}