2、使用spring提供的RestTemplate发送http请求到其他服务

场景:使用spring提供的RestTemplate发送http请求到商品服务

(1)在shop_service_order工程中ProductApplication启动类中配置RestTemplate

//配置RestTemplate交给spring管理
@BeanpublicRestTemplategetRestTemplate() {
return new RestTemplate();    
}

(2)编写下订单方法

@PostMapping("/{id}")publicStringorder(Integernum) {
//通过restTemplate调用商品微服务
Product object=restTemplate.getForObject("http://127.0.0.1:9002/product/1", Product.class);
System.out.println(object);
return"操作成功";    
}

3.5.4 硬编码存在的问题

至此已经可以通过RestTemplate调用商品微服务的RESTFul API接口。但是我们把提供者的网络地址(ip,端口)等硬编码到了代码中,这种做法存在许多问题:
1、应用场景有局限
2、无法动态调整
在这里插入图片描述

那么应该怎么解决呢?就需要通过注册中心动态的对服务注册和服务发现。

发布了55 篇原创文章 · 获赞 4 · 访问量 3121

猜你喜欢

转载自blog.csdn.net/qq_41347385/article/details/104901635