1. 程式人生 > 其它 >學習spring cloud記錄3-服務遠端呼叫

學習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服務