RestTemplate 是SpringBoot提供的一个Rest远程调用工具
它的常用方法:

  • getForObject() - 执行get请求
  • postForObject() - 执行post请求

之前的系统结构是浏览器直接访问后台服务
image.png
后面我们通过一个Demo项目演示 Spring Cloud 远程调用
image.png
下面我们先不使用ribbon, 单独使用RestTemplate来执行远程调用

  1. 新建 ribbon 项目
  2. pom.xml
  3. application.yml
  4. 主程序
  5. controller
  6. 启动,并访问测试

pom.xml

  • eureka-client 中已经包含 ribbon 依赖

    application.yml

    ```c spring: application: name: ribbon

server: port: 3001

eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

  1. <a name="Xxrd7"></a>
  2. ## 主程序
  3. - 创建 `RestTemplate` 实例
  4. `RestTemplate` 是用来调用其他微服务的工具类,封装了远程调用代码,提供了一组用于远程调用的模板方法,例如:`getForObject()`、`postForObject()` 等
  5. ```java
  6. @EnableDiscoveryClient
  7. @SpringBootApplication
  8. public class Sp06RibbonApplication {
  9. //创建 RestTemplate 实例,并存入 spring 容器
  10. @Bean
  11. public RestTemplate getRestTemplate() {
  12. return new RestTemplate();
  13. }

RibbonController

@RestController
public class RibbonController {
    @Autowired
    private RestTemplate rt;

    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
        //向指定微服务地址发送 get 请求,并获得该服务的返回结果 
        //{1} 占位符,用 orderId 填充
        return rt.getForObject("http://localhost:8001/{1}", JsonResult.class, orderId);
    }

    @PostMapping("/item-service/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {
        //发送 post 请求
        return rt.postForObject("http://localhost:8001/decreaseNumber", items, JsonResult.class);
    }