1. 程式人生 > 實用技巧 >實戰二:編寫微服務邏輯及微服務間呼叫

實戰二:編寫微服務邏輯及微服務間呼叫

一,參照上一篇建立好微服務結構後,按業務需求編寫各微服務邏輯

二,服務註冊

  1,安裝nacos:下載,解壓,執行startup.cmd

  2,訪問http://localhost:8848/nacos ,登入賬號密碼均為nacos,可以看到註冊的服務列表及配置列表

  3,上一節在微服務中已經引入了nacos服務註冊依賴和openfeign依賴,如下:(nacos還可以作為配置中心,這裡先只引入服務註冊依賴,不引入配置中心依賴)

注1:此入只引入了nacos服務註冊依賴,未引入nacos配置中心依賴
<
dependency> <groupId>com.alibaba.cloud</
groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
  注2:openfeign用於微服務間的httprest呼叫 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</
artifactId> </dependency>

  4,配置nacos服務註冊資訊

spring.application.name=user
spring.cloud.nacos.server-addr=localhost:8848
spring.cloud.nacos.discovery.server-addr=${spring.cloud.nacos.server-addr}

  5,重啟微服務,重新整理http://localhost:8848/nacos,可以看到剛剛的微服務已經註冊到了nacos了

三,微服務間呼叫

  1,如使用者服務需要呼叫商品服務介面,取得商品服務的資訊,則在使用者服務入口檔案開啟@EnableFeignClients註解

  2,新建clients包,建立ProductClient介面,參照商品服務編寫介面,引數與路徑要與商品服務一致,可以依據商品服務直接拷貝其方法定義的程式碼

  3,在ProductClient類上新增@FeignClient(value = "product")註解,即指定需要連線的服務名

  4,在使用者服務的controller中注入ProductClient,呼叫介面中定義的方法,取得商品資料

注:openfeign已經集成了ribbon,自動進行負載均衡