SpringCloud服務的發現與調用實例分析

蝸牛 互聯網技術資訊 2022-07-18 13 0

這篇文章主要介紹“SpringCloud服務的發現與調用實例分析”,在日常操作中,相信很多人在SpringCloud服務的發現與調用實例分析問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringCloud服務的發現與調用實例分析”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

一、服務提供者

  • 新建Maven項目provider

  • 引入項目依賴

????<parent>
????????<groupId>com.cxy965</groupId>
????????<artifactId>parent</artifactId>
????????<version>1.0-SNAPSHOT</version>
????????<relativePath>../parent/pom.xml</relativePath>
????</parent>
????<dependencies>
????????<dependency>
????????????<groupId>org.springframework.boot</groupId>
????????????<artifactId>spring-boot-starter-web</artifactId>
????????</dependency>
????????<dependency>
????????????<groupId>org.springframework.cloud</groupId>
????????????<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
????????</dependency>
????</dependencies>

新建配置文件application.yml

server:
? port: 8002
spring:
? application:
? ? name: provider
eureka:
? client:
? ? service-url:
? ? ? defaultZone: http://localhost:8001/eureka/
? ? fetch-registry: true

創建啟動類和服務接口,為了簡便,暫時將服務接口放在了啟動類,實際項目中,最好還是要放在controller中。

@EnableEurekaClient
@SpringBootApplication
@RestController
public?class?ProviderApplication?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(ProviderApplication.class,?args);
????}
????@GetMapping("/hello")
????public?String?hello(String?name)?{
???????return?"Hello?"+name;
????}
}

啟動驗證一下,可以正常返回。

二、服務消費者

  • 參考provider項目創建consumer項目

  • 修改配置文件中的端口和應用名稱為8003、consumer

  • 創建啟動類和服務消費代碼

@EnableEurekaClient
@SpringBootApplication
@RestController
public?class?ConsumerApplication?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(ConsumerApplication.class,?args);
????}
????@Bean
????RestTemplate?restTemplate()?{
????????return?new?RestTemplate();
????}
????@Autowired
????DiscoveryClient?discoveryClient;
????@Autowired
????RestTemplate?restTemplate;
????@GetMapping("/hello")
????public?String?hello(String?name)?{
????????List<ServiceInstance>?list?=?discoveryClient.getInstances("provider");
????????ServiceInstance?instance?=?list.get(0);
????????String?host?=?instance.getHost();
????????int?port?=?instance.getPort();
????????String?returnInfo?=?restTemplate.getForObject("http://"?+?host?+?":"?+?port?+?"/hello?name={1}",?String.class,?name);
????????return?returnInfo;
????}
}

啟動驗證一下

SpringCloud服務的發現與調用實例分析  springcloud 第1張

可以看到,我們調用8003消費者服務,消費者服務又調用了8002服務提供者的接口,并正確返回了結果。

到此,關于“SpringCloud服務的發現與調用實例分析”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注蝸牛博客網站,小編會繼續努力為大家帶來更多實用的文章!

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:niceseo99@gmail.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

評論

2018人人澡人摸人人添_月夜影视在线观看资源_一本二卡三卡四卡乱码小说_tobu8在线观看下载