首页 新闻 会员 周边

能解释下RestTemplate的作用,或者实际运用场景

0
[已解决问题] 解决于 2019-07-16 22:17

能解释下RestTemplate的作用吗?是用来调用接口的同时对外开放接口?也就是中转接口服务,看了很多例子,都是可以调用api接口,同时,自己也可以在浏览器中进行访问传参,这个是为了和前端进行交互?

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RestTemplateController {
@Autowired
private RestTemplate restTemplate;

/*// Restful服务对应的url地址,解决硬编码问题
@Value("${user.userServicePath}")
private String userServicePath;*/

@GetMapping("/template/{id}")
public User findById(@PathVariable Long id) {
    // http://localhost:7900/user/是前面服务的对应的url
    User u=new User();
    u = this.restTemplate.getForObject("http://localhost:8080/user/" + id, User.class);

// u.setId(id);
System.out.println(u);
return u;
}
}

花开半夏雨的主页 花开半夏雨 | 初学一级 | 园豆:6
提问于:2019-03-01 11:39
< >
分享
最佳答案
1

这里有篇博客,你看有帮助吗:
https://blog.csdn.net/u012702547/article/details/77917939

奖励园豆:5
三人乐乐 | 老鸟四级 |园豆:4819 | 2019-03-01 14:20
其他回答(1)
0

上面的很详细了,就是个很好的封装工具,功能也吊逼逼,正常调url比如新建个HttpPost去设置一些什么header啥的再去调用,get的又是另一个,这个RestTemplate就是相当于小霸王4合1,哪里不会点哪里

才小有 | 园豆:232 (菜鸟二级) | 2019-03-05 17:50

这个是,调用开放的接口服务,只是作用一,作用二:调用别个接口的同时,把自己当做接口服务对外开放了?

支持(0) 反对(0) 花开半夏雨 | 园豆:6 (初学一级) | 2019-03-08 10:52

@GetMapping("/template/{id}")
public User findById(@PathVariable Long id) {
// http://localhost:7900/user/是前面服务的对应的url
// User u = this.restTemplate.getForObject("http://localhost:8080/user/" + id, User.class);
User u=new User();
u.setId(id);
System.out.println(u);
return u;
}

魔怔了,这个@GetMapping不是RestTemplate的功能,其实应该是使用RestTemplate快速调用接口,同时可以使用spring的注解同时把RestTemplate作为中转接口开放出去

支持(0) 反对(0) 花开半夏雨 | 园豆:6 (初学一级) | 2019-03-08 10:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册