使用restTemplate远程调controller路径取数据

网友投稿 570 2022-12-17

使用restTemplate远程调controller路径取数据

使用restTemplate远程调controller路径取数据

目录restTemplate远程调controller路径取数据首先要写相关配置类,举例:然后调目标cotroller层,比如目标cotroller层为需要用post的方法去调再比如目标controller层为需要用get的方法去调通过Spring的RestTemplate进行跨模块调用相关代码如图下所示:相关代码可参考图下所示:运行结果如下所示:

restTemplate远程调controller路径取数据

Spring的RestTemplate提供了很多对HTTP method的支持,这里主要说常用的gehttp://t和post。

使用环境为springboot

首先要写相关配置类,举例:

@Configuration

public class Config {

@Autowired

RestTemplateBuilder builder;

@Bean

public RestTemplate restTemplate() {

return builder.build();

}

}

然后调目标cotroller层,比如目标cotroller层为

@RestController

@RequestMAPPing("/aaa")

public class TemplateController {

@PostMapping(value = "/ppp")

public List getInfo(@RequestBody String sid) {

...

return stuService.getId(areaId);

}

}

需要用post的方法去调

@Autowired

private RestTemplate restTemplate;

public List getMsg() {

String id = "111";

HttpEntity entity = buildEntity(id);

String url = "http://ip:port/aaa/ppp";

return restTemplate.postForObject(url, entity, List.class);

}

private HttpEntity buildEntity(String id) {

jsONObject jo = new JSONObject();

jo.put("sid", id);

String requestJson = jo.toJSONString();

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

return new HttpEntity(requestJson, headers);

}

再比如目标controller层为

@RestController

@RequestMapping(value = "/aaa")

public class StudentController {

@GetMapping(value = "/ggg")

public Set queryStudent(@RequestParam(value = "code") String code,

@RequestParam(value = "objectKey") String objectKey,

@RequestParam(value = "studentId") Integer studentId) {

return sService.get(code, objectKey, kindId);

}

}

需要用get的方法去调

@Autowired

private RestTemplate restTemplate;

public Set queryStudent(String ip, int port,EventRelationTask eventRelationTask) {

Integer studentId = eventRelationTask.getStudentId();

String code = eventRelationTask.getCode();

String objectKey = eventRelationTask.getObjectKey();

String url =

"http://" + ip + ":" + port + Student.PROJECTNAME + "event/queryparentnode?code=" + code + "&objectKey=" + objectKey + "&studentId=" + studentId;

Set students = new HashSet<>();

students = restTemplate.getForObject(url, Set.class); //主要这个方法

if (students != null) {

return students;

}

return new HashSet();

}

通过Spring的RestTemplate进行跨模块调用

Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现对象与json的序列化和反序列化。首先在项目中新建controller方法

相关代码如图下所示:

接着我们在另外一个项目中的启动类的位置注册一个RestTemplate实例

相关代码可参考图下所示:

然后创建HttpTestController使用RestTemplate中最简单的一SLKsg个功能getForEntity发起了一个get请求去调用前一个项目中服务端的数据并返回结果。

最后访问http://localhost:808SLKsg0/httpTestController/queryByname?name=张三就能看到list打印传递的值。需要注意的是图1是第一个项目请求的,图2是第二个项目通过跨服务跨项目请求得来的,它们两者的端口号是不一样的

运行结果如下所示:

(图1)

(图2)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:IDEA2021安装及常用功能设置
下一篇:SpringBoot中@Transiactional注解没有效果的解决
相关文章

 发表评论

暂时没有评论,来抢沙发吧~