spring boot openfeign从此和httpClient说再见详析

时间:2021-05-19

前言

在微服务设计里,服务之间的调用是很正常的,通常我们使用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,以后开发服务对服务调用就可以解耦了!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章