Spring Cloud
  • Introduction
  • 网站架构演变过程
    • 微服务架构
  • Spring Cloud 简介
  • 服务的注册与发现
    • 其他知识
      • Zookeeper与Eureka区别
      • DiscoveryClient 与@EnableEurekaServer
    • Zookeeper
    • Consul
    • Eureka
      • 搭建注册中心
      • 高可用注册中心
      • Eureka详解
  • 服务消费者
    • RestTemplate
    • 服务消费者(rest+ribbon)
      • 此时架构
    • 服务消费者(Feign)
  • 断路器(Hystrix)
    • 基础入门
  • API Gateway(Zuul)
    • 基础入门
  • 分布式配置中心(Config)
    • 基础入门
  • SpringCloud Bus
  • 链路跟踪(Sleuth)
  • 数据流(Stream)
  • Dubbo
    • Untitled
Powered by GitBook
On this page
  • GET请求
  • getForEntity
  • getForObject
  • POST请求
  • PostForEntity
  • postForObject
  • PUT请求
  • DELETE请求

Was this helpful?

  1. 服务消费者

RestTemplate

GET请求

getForEntity

getForEntity方法的返回值是一个ResponseEntity<T>,ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等

@RequestMapping("/getForEntity")
public ResponseEntity<String> getForEntity() {
      ResponseEntity<String> response = restTemplate.getForEntity("http://app-itmayiedu-member/getMember",
                 String.class);
      System.out.println("statusCode:" + response.getStatusCode());
      System.out.println("Body:" + response.getBody());
      return response;
}

getForEntity的第一个参数为我要调用的服务的地址,这里我调用了服务提供者提供的/hello接口,注意这里是通过服务名调用而不是服务地址,如果写成服务地址就没法实现客户端负载均衡了。

getForEntity第二个参数String.class表示我希望返回的body类型是String

拿到返回结果之后,将返回结果遍历打印出来

Get请求传递参数

@RequestMapping("/getForOrderEntity2")
public ResponseEntity<String> getForEntity2(String name) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("name", name);
      ResponseEntity<String> response = restTemplate.getForEntity("http://app-itmayiedu-member/getUser?name={name}",
                 String.class, map);
      System.out.println("statusCode:" + response.getStatusCode());
      System.out.println("Body:" + response.getBody());
      return response;
}

可以用一个数字做占位符,最后是一个可变长度的参数,来一一替换前面的占位符

也可以前面使用name={name}这种形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值

getForObject

getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject,举一个简单的例子,如下:

@RequestMapping("/getOrder")
public String getOrder() {
      // 有两种方式,一种是采用服务别名方式调用,另一种是直接调用 使用别名去注册中心上获取对应的服务调用地址
      String url = "http://app-itmayiedu-member/getMember";
      String result = restTemplate.getForObject(url, String.class);
      System.out.println("订单服务调用会员服务result:" + result);
      return result;
}

POST请求

PostForEntity

postForObject

如果你只关注,返回的消息体,可以直接使用postForObject。用法和getForObject一致

PUT请求

DELETE请求

Previous服务消费者Next服务消费者(rest+ribbon)

Last updated 4 years ago

Was this helpful?