在最近做的项目中,由于之前做的各个服务都是相互独立的,但是业务要求调用其他已做好的服务的功能,于是就有了正在做的项目调用已经上线的服务的需求。
一、背景描述
公司网站(服务A)改版升级中,由于需要调用商品中心(服务B)的接口,查询出公司的所有产品,并展示在网站上。由于这两个是独立的服务,相互之前没有关联性,所以会牵出一个问题?这服务A怎么调用服务B。
两个服务的项目结构如下:
服务A:公司网站采用的是Spring boot(2.0.0) + Maven项目结构
服务B:商品中心采用的是标准的微服务项目结构
二、配置方法
2.1 添加maven依赖
对于spring boot 2.0.0版本以上的,引用openfeign,低于这个版本的,
<!--引入feign--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.0.2.RELEASE</version> </dependency>
2.2 添加@EnableFeignClients注解
在服务A的启动类上添加@EnableFeignClients注解,使得该服务支持FeignClients功能。
@EnableScheduling @SpringBootApplication(scanBasePackages={"com.iot.shcs","com.iot.pwfm"}) //开启事务管理 @EnableTransactionManagement @MapperScan({"com.iot.pwfm.context.dao","com.iot.pwfm.context.*.dao"}) @EnableFeignClients public class WebsiteApplication { public static void main(String[] args) { SpringApplication.run(WebsiteApplication .class, args); } }
2.3 配置文件application.properties中添加路径
配置文件中添加如下配置,然后在类中通过@FeignClient注解获取
#################调用商品中心服务##################### goodsUrl=http://dev.iot.com:8200 dingDingUrl=http://dev.iot.com:8022/approvalProcess/approvalProcessCreate
2.4 服务A中添加服务B的接口
通过@FeignClient注解获取在配置文件中的url地址
@FeignClient(url = "${goodsUrl}", name = "itemCategory") public interface ItemCategoryApi { /** * 获取商品类目二维列表 * * @return 商品类目二维列表 */ @GetMapping("/itemcategory/tree/get") CommResponse<List<CategoryDTO>> queryTree(); }
2.5 调用此接口
把这个接口当成本项目中的一个接口类正常注入调用即可。如图所示:
完结!