温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringCloud微服务中的Rest及请求方式是什么

发布时间:2022-02-28 15:54:16 来源:亿速云 阅读:158 作者:iii 栏目:开发技术

这篇“SpringCloud微服务中的Rest及请求方式是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringCloud微服务中的Rest及请求方式是什么”文章吧。

一、什么是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请求

  • getForObject

@GetMapping("get/{id}")
public CommonResult getUser(@PathVariable Long id) {
    CommonResult commonResult 
    	= restTemplate.getForObject(Url + "/user/{1}", CommonResult.class, id);
    
    return commonResult
}
  • getForEntity

@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请求

  • postForObject

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

@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);
}

以上就是关于“SpringCloud微服务中的Rest及请求方式是什么”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI