通过RestTemplate进行微服务间(通过服务名)的调用

Bertha 。 2022-01-17 02:27 1154阅读 0赞

样例:

  1. @Slf4j
  2. @RestController
  3. @RequestMapping(path = "/test")
  4. public class TestController {
  5. @Autowired
  6. @LoadBalanced
  7. private RestTemplate restTemplate;
  8. @ApiOperation(value = "test", notes = "test")
  9. @GetMapping(path = "/test")
  10. public void test() {
  11. Map<String, String> paramMap = new HashMap<>();
  12. paramMap.put("channel", "11111");
  13. paramMap.put("id", "22222");
  14. String url = "http://SERVICE/auth-api/v1/inn/getInnRandomId?channel={channel}&id={id}";
  15. ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url, JSONObject.class, paramMap);
  16. if (responseEntity.getStatusCode().is2xxSuccessful()) {
  17. Map<String, Object> innInfoBody = responseEntity.getBody();
  18. innInfoBody.forEach((k, v) -> log.debug("key:" + k + "value:" + v));
  19. } else {
  20. log.debug("接口访问失败");
  21. }
  22. }
  23. }

在这里插入图片描述

注意
1.微服务间的访问可以通过http://服务名/映射链接 这种方式来访问
2.如果调用的服务存在上下文,那么则要通过http://服务名/服务上下文/映射链接 这种方式来访问。
3.当项目application.yml配置了服务上下文,但是在访问链接不想带上服务配置的上下文访问,可以通过以下配置方式来实现(增加eureka.instance.home-page-url-path配置)。

  1. eureka:
  2. client:
  3. service-url:
  4. defaultZone: http://172.11.62.183:6600/eureka/,http://172.11.62.184:6600/eureka/,http://172.11.62.185:6600/eureka/,http://172.25.62.50:7200/eureka/
  5. instance:
  6. home-page-url-path: ${server.servlet.context-path}

发表评论

表情:
评论列表 (有 0 条评论,1154人围观)

还没有评论,来说两句吧...

相关阅读