学习spring cloud记录3-服务远程调用

前言

记录一个非常简单的远程调用方式,在spring cloud微服务中,服务之间时如何进行调用的?在学习通过服务名调用方式之前,先学一种非常简单的调用方式,那就是通过url进行调用,此url为ip+端口号+地址的方式

使用

spring提供了工具RestTemplate,在每次进行调用时需要new一个RestTemplate对象,然后进行调用接口,在spring cloud中,可以在启动类中注册RestTemplate对象,在后面的代码中直接注入即可,无需new对象。

在启动类中添加代码:

 1 package priv.sinoam.demoorder;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.web.client.RestTemplate;
 7 
 8 /**
 9  * @author 龙谷情
10  */
11 @SpringBootApplication
12 public class DemoOrderApplication {
13 
14     public static void main(String[] args) {
15         SpringApplication.run(DemoOrderApplication.class, args);
16     }
17 
18     /**
19      * 创建RestTemplate并注入Spring容器
20      * @return
21      */
22     @Bean
23     public RestTemplate restTemplate(){
24         return new RestTemplate();
25     }
26 
27 }

调用时如此调用即可:

 1     @Autowired
 2     private RestTemplate restTemplate;
 3     public Map<String, Object> test1() {
 4         DemoOrderInfo demoOrderInfo = demoOrderInfoDao.selectById(1);
 5         Map<String, Object> map = new HashMap<>(16);
 6         map.put("order", demoOrderInfo);
 7         //调用demo-user里面的请求
 8         String url = "http://localhost:9001/demouser/user/test";
 9         Map<String, Object> map2 = restTemplate.getForObject(url, Map.class);
10         map.put("user", map2);
11         return map;
12     }

本次实验在order服务中调用user接口。第9行可根据需要的类型进行修改,本次使用Map类型。

结束

一次非常简单的记录,时间少,就少记录一点。下面学习记录Eureka服务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值