脱离spring cloud使用feign
优雅的http接口调用-feign。
spring-cloud-feign是spring cloud微服务之间调用封装的功能,由于feign的封装和解耦做的比较好,因此脱离spring cloud也能使用。
Spring boot项目使用feign
项目背景:spring boot 2.2.5.RELEASE
引入Maven
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
启动注解
和spring cloud项目一样,同样需要在启动类上添加注解
@EnableFeignClients
Feign接口
接下来直接写feign的接口就行了,和产品spring cloud项目相比,这里的服务地址不再是服务名,而换成了具体的url
@FeignClient(url = "${ca.url}", name = "caClient")
public interface CaClient {
@PostMapping(value = "ca", headers = "TOKEN=${ca.token}")
Result<String> ca(@RequestBody CaDto dto);
}
测试验证
@Slf4j
@SpringBootTest(classes = CaApplication.class)
@RunWith(SpringRunner.class)
public class CaClientTest {
@Autowired
private CaClient caClient;
@Test
public void testOpenApiPartner() {
Result result = caClient.ca(CaDto
.builder()
.partnerId("123")
.type("platform")
.build());
log.info(JsonUtils.beanToString(result));
Assert.isTrue(result != null, "返回空");
Assert.isTrue(result.isSuccess(), "返回false");
Assert.isTrue(result.getCode() == 200, "返回错误");
}
}