springboot~openfeign從此和httpClient說再見
阿新 • • 發佈:2018-12-29
在微服務設計裡,服務之間的呼叫是很正常的,通常我們使用httpClient來實現對遠端資源的呼叫,而這種方法需要知識服務的地址,業務介面地址等,而且需要等他開發完成後你才可以去呼叫它,這對於整合開發來說,不是什麼好事 ,產生了A業務與B業務的強依賴性,那麼我們如何進行解耦呢,答案就是openfeign框架,它與是springcloudy裡的一部分。
1 新增包引用
'org.springframework.cloud:spring-cloud-starter-openfeign',
注意如果你沒有引用springcloudy版本人有太多,需要先宣告它
dependencyManagement { imports { mavenBom"org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
2 定義profile相關配置
//預設的一些檔案路徑的配置 sourceSets { integTest { java.srcDir file('src/test/java') resources.srcDir file('src/test/resources') } } task integTest(type: Test) { testClassesDirs= sourceSets.test.output.classesDirs classpath = sourceSets.test.runtimeClasspath }
3 定義服務介面,定義偽方法,就是服務裡的方法,你要知識方法引數和它的返回值,實現不用管,只在單元測試裡MOCK就可以
package test.lind.javaLindDay.feignClientDemo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Profile;import org.springframework.web.bind.annotation.GetMapping; /** * 模擬其他服務. */ @Profile("!integTest") @FeignClient(name = "serviceName") public interface MockClient { @GetMapping(path = "/balanceSheet/{clientCode}") String balanceSheet(String clientCode); }
4 Profile的作用
profile就是環境變數,你在類上通過ActiveProfile去啟用它,在使用它時,有過Profile註解來使用上,上面程式碼中MockClient物件不能在integTest環境下使用。
5 新增MOCK實現,它是自動注入的,所以宣告@Bean註解
package test.lind.javaLindDay; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import test.lind.javaLindDay.feignClientDemo.MockClient; @Configuration @Profile("integTest") public class MockClientTest { @Bean public MockClient mockClient() { MockClient client = mock(MockClient.class); when(client.balanceSheet( anyString())) .thenReturn("OK"); return client; } }
6 新增單元測試,注意在單元測試上一定要指定它的環境變數
package test.lind.javaLindDay; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import test.lind.javaLindDay.feignClientDemo.MockClient; @RunWith(SpringRunner.class) @SpringBootTest //指定profile環境 @ActiveProfiles("integTest") public class JavaLindDayApplicationTests { @Autowired MockClient mockClient; @Test public void testMockClient() { assertEquals(mockClient.balanceSheet("OK"), "OK"); } }
執行測試後,MockClient將會被注入,它將使用Mock實現類,因為只有Mock實現類的Profile是指向integtest環境的。
有了openfeign,以後開發服務對服務呼叫就可以解耦了!