码迷,mamicode.com
首页 > 其他好文 > 详细

SprirngBoot微服务之间的交互—— restTemplate

时间:2017-10-30 18:25:19      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:response   地方   ati   除了   ...   utils   交互   object   smo   

一 例:需要在storage服务中请求utils服务的某个接口(两个服务都已向同一台eureka server 注册)

步骤:

1 在utils创建需被调用的接口

@RestController
@RequestMapping("/api")
public class CheckIPResource {
      @PostMapping("/checkip")
      public String checkIP(@RequestBody TestEntity testEntity) {
          //处理数据
          // 返回结果
          return "404";
      }
}

2 在storage的主类里创建restTemplate

位置: com.ejtone.ejt1.StorageApp
?
public class StorageApp {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){ return new RestTemplate(); }
}

3 在storage需要调用utils接口的地方去调用

public class CheckIpService {
?
    @Autowired
    private RestTemplate restTemplate;
    
    public void testFrom(TestEntity testEntity){
    
      // postForObject   请求方式:post  常用的请求方式还有get,具体见下方第二点
      // http://utils/api/checkip  utils:是utils微服务向eureka server注册时的名称,后接具体位置
      // new HttpEntity<>(testEntity) 请求体 --可带请求头,具体见下方第三点
      //String.class 请求响应返回后的数据的类型
      restTemplate.postForObject("http://utils/api/checkip",
                                 new HttpEntity<>(testEntity),
                                 String.class);
    }
}

二 请求方式除了上面使用的post之外,还有getForObject:

// 参数url是http请求的地址
// Class responseType  请求响应返回后的数据的类型
// String... urlVariables 请求中需要设置的参数
RestTemplate.getForObject(String url, Class responseType, String... urlVariables)
?
例如下方,url上带着一个参数{id},最后执行该方法会返回一个String类型的结果,后面的id是请求的一个具体变量。
template.getForObject(url + "get/{id}", String.class, id);

三 HttpEntity<>(请求体,请求头)

public class ParService {
    @Autowired
    private RestTemplate restTemplate;
    
    public Par setPar(TxtFileVM txtFileVM, HttpServletRequest request) {
            //创建一个请求头
            HttpHeaders headers = new HttpHeaders();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                String value = request.getHeader(key);
                headers.add(key, value);
            }
            txtPath = restTemplate.postForObject("http://storage/api/create/txtfile",
                                                  new HttpEntity<>(txtFileVM,headers),
                                                  String.class);
}

 

SprirngBoot微服务之间的交互—— restTemplate

标签:response   地方   ati   除了   ...   utils   交互   object   smo   

原文地址:http://www.cnblogs.com/serena25/p/7755418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!