RestTemplate 是一个HTTP客户端,在Spring Cloud的服务调用方使用它我们可以方便的调用HTTP接口,支持GET、POST、PUT、DELETE等方法。
首先注入Bean对象
@Configuration public class MyConfig { @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
@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); } }
@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(); }
@PutMapping("/update") public CommonResult update(@RequestBody User user) { restTemplate.put(Url + "/user/update", user); return new CommonResult("操作成功",200); }
@DeleteMapping("/delete/{id}") public CommonResult delete(@PathVariable Long id) { restTemplate.delete(Url + "/user/delete/" + id, null); return new CommonResult("操作成功",200); }
到此这篇关于详解SpringCloud微服务之Rest的文章就介绍到这了,更多相关SpringCloud Rest内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
免责声明:本站发布的内容(图片、视频和文字)以原创、来自互联网转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系QQ:712375056 进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
Copyright © 2009-2021 56dr.com. All Rights Reserved. 特网科技 特网云 版权所有 珠海市特网科技有限公司 粤ICP备16109289号
域名注册服务机构:阿里云计算有限公司(万网) 域名服务机构:烟台帝思普网络科技有限公司(DNSPod) CDN服务:阿里云计算有限公司 中国互联网举报中心 增值电信业务经营许可证B2
建议您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流浏览器浏览本网站