轻松与外来客户进行REST通信
在這個例子中,我們將向您展示如何使用Feign客戶端開發一個簡單的Spring Boot Application,以使用Weather REST服務。
Spring Boot是基于Java的框架,可簡化Web和企業應用程序的構建。 Spring Boot具有嵌入式Tomcat,提供“啟動器”依賴關系,并且不需要配置XML。
Feign是由Netflix開發的用于實現REST API客戶端的聲明性框架。 Feign允許構建REST客戶端來聲明和注釋接口,實際實現在運行時提供。
1.項目環境
此示例將使用以下工具實現:
有了這些信息,讓我們開始吧!
2.創建一個Spring Boot應用程序
 單擊文件->新建->項目 
創建一個Spring Boot應用程序-步驟1
選擇Spring Initializr并選擇適當的JDK版本。
創建一個Spring Boot應用程序-步驟2
添加組和工件名稱 。
選擇Gradle Project,然后為您的項目輸入一個版本 。
創建一個Spring Boot應用程序-步驟3
在下一個窗口中,選擇以下選項:
- 核心-> DevTools
- 網頁->網頁
- 云->云引導
創建一個Spring Boot應用程序-步驟4
選擇項目的位置,然后單擊“ 完成”按鈕。
創建一個Spring Boot應用程序-步驟5
和瞧!
您有一個Spring Boot應用程序。
創建一個Spring Boot應用程序–步驟6
3.創建一個控制器并啟動應用程序
創建一個名為FeignController類。 將Java類注釋為Controller并實現GET方法,該方法返回帶有偽數據的ResponseEntity 。 之后,我將使用真實信息來完成地圖。
package com.example.feign.controller;@RestController public class FeignController {private final IWeatherClient weatherClient;@Autowiredpublic FeignController(IWeatherClient weatherClient) {this.weatherClient = weatherClient;}@GetMapping(path = "/weather")ResponseEntity<Map> getWeather() {return ResponseEntity.ok(weatherClient.getWeather().getBody());} }使用用于部署應用程序的端口編輯文件application.properties。
server.port=9090 最后,運行并測試該應用程序的第一個版本。 
測試應用
4.假冒客戶實施
編輯build .gradle文件,并包括以下依賴項:
compile('org.springframework.boot:spring-boot-starter-web-services') compile('org.springframework.cloud:spring-cloud-starter-openfeign') compile('org.springframework.cloud:spring-cloud-starter-config') 記住運行build Gradle任務。 
運行構建Gradle任務
創建一個程序包和一個接口。
它將是我們的假客戶。
我將其命名為IWeatherClient
創建一個新的班級
將界面注釋為FeignClient并添加一種獲取天氣的方法。
注釋@FeignClient要求您包括服務的名稱和URL。
在這種情況下,我選擇了諸如name之類的數據,并為URL使用了一個屬性。
package com.example.feign.feign;@FeignClient(name = "data", url = "${feign.client.url}") public interface IWeatherClient {@RequestMapping(method = RequestMethod.GET)ResponseEntity<Map> getWeather();}為接口添加一個實現。 如果在調用該服務時出現問題,這將是一個后備。 在這種情況下,我沒有后備功能,因此我將返回null。
package com.example.feign.feign.imp;@Component public class WeatherFallback implements IWeatherClient {@Overridepublic ResponseEntity<map> getWeather() {return null;}} </map>注釋主類以啟用Feign客戶。 注釋@EnableFeignClients要求您包括基本軟件包。
package com.example.feign;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication @EnableFeignClients(basePackages = {"com.example.feign.feign","com.example.feign.controller"}) public class FeignApplication {public static void main(String[] args) {SpringApplication.run(FeignApplication.class, args);} } 最后,在控制器中使用偽客戶端,然后再次運行該應用程序。 
創建Feign客戶的結果
5.結論
此項解釋了如何使用Feign構建一個聲明性HTTP客戶端以使用Weather API。 Feign的目標是降低與HTTP APIS統一綁定分母的復雜性,而不管其是否平靜。
6.下載項目
下載您可以在此處下載此示例的完整源代碼: Feign示例
翻譯自: https://www.javacodegeeks.com/2018/10/making-rest-communication-easy-with-feign-clients.html
總結
以上是生活随笔為你收集整理的轻松与外来客户进行REST通信的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 飞鱼星交换机设置(飞鱼交换机如何配置)
- 下一篇: 通过Spring Boot了解H2 In
