亲宝软件园·资讯

展开

SpringCloud Rest 详解SpringCloud微服务之Rest

ProChick 人气:1
想了解详解SpringCloud微服务之Rest的相关内容吗,ProChick在本文为您仔细讲解SpringCloud Rest的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringCloud,Rest,SpringCloud微服务,下面大家一起来学习吧。

一、什么是RestTemplate?

RestTemplate 是一个HTTP客户端,在Spring Cloud的服务调用方使用它我们可以方便的调用HTTP接口,支持GET、POST、PUT、DELETE等方法。

二、四种请求方式

首先注入Bean对象

@Configuration
public class MyConfig {
  @Bean
  public RestTemplate restTemplate(){
      return new RestTemplate();
  }
}

2.1 GET请求

@GetMapping("get/{id}")
public CommonResult getUser(@PathVariable Long id) {
    CommonResult commonResult 
    	= restTemplate.getForObject(Url + "/user/{1}", CommonResult.class, id);
    
    return commonResult
}
@GetMapping("/get/{sex}")
public CommonResult getUser(@PathVariable String sex) {
    ResponseEntity<CommonResult> entity 
        = restTemplate.getForEntity(Url + "/user/{女}", CommonResult.class, sex);
    
    if (entity.getStatusCode().is2xxSuccessful()) {
        return entity.getBody();
    } else {
        return new CommonResult("操作失败", 500);
    }
}

2.2 POST请求

@PostMapping("/add")
public CommonResult add(@RequestBody User user) {
    CommonResult commonResult
    	= restTemplate.postForObject(Url + "/user/add", user, CommonResult.class);
    
    return commonResult;
}
@PostMapping("/add")
public CommonResult add(@RequestBody User user) {
    CommonResult commonResult
    	= restTemplate.postForEntity(Url + "/user/add", user, CommonResult.class)
    return commonResult.getBody();
}

2.3 PUT请求

@PutMapping("/update")
public CommonResult update(@RequestBody User user) {
    restTemplate.put(Url + "/user/update", user);
    
    return new CommonResult("操作成功",200);
}

2.4 DELETE请求

@DeleteMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
   restTemplate.delete(Url + "/user/delete/" + id, null);
   
    return new CommonResult("操作成功",200);
}

加载全部内容

相关教程
猜你喜欢
用户评论