接上篇《微服务实战spring cloud alibaba(六)如何处理全局异常》,上一篇我们实现了全局异常,那么我们知道微服务与微服务之间可以相互调用,同时我们不需要自己写httpclient,直接使用openfeign就可以了。所以这篇我们简单来实现一下openfeign。
整个的业务就是,通过user-service端,调用goods-service端。可以想象的业务是通过某一商户,查询他出售的某个商品的剩余库存。所以整体流程是:
话不多说,直接上代码(后面我们再单独讲解openfeign的一些知识点)
一、添加依赖
1.1、在总的pom里面的dependencyManagement里面添加spring cloud依赖。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR4</version> <type>pom</type> <scope>import</scope> </dependency>
1.2、在u-common的pom里面添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
二、在u-comon项目里面新增GoodsFeignClient.java
package com.umall.common.feigns; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * */ /** * @author Administrator * */ @FeignClient(value = "goods-service") @RestController public interface GoodsFeignClient { @RequestMapping(value = "/good/user/{goodId}", method = RequestMethod.GET) Integer getBusinessGoodStock(@PathVariable("goodId") Integer goodId); }
这里的feignClient里面的value需要写对应调用的微服务name,比如我们这里是用来调用goods-service的,所以这里就写good-service,如果是其他的service,则写其他service的name。
三、在user-service编写对外的controller,然后内部通过feignClient调用goods-service
@Resource private GoodsFeignClient feign; @RequestMapping(value = "/user/good/{goodId}", method = RequestMethod.GET) public BaseResponse getBusinessGoodStock(@PathVariable("goodId") Integer goodId) { Integer stock = feign.getBusinessGoodStock(goodId); return BaseResponse.success(stock); }
四、访问测试
然后我们访问http://localhost:9001/user/good/1
到这里我们看到请求到了库存是12。这个12还记得吗?之前在nacos的配置中心这篇文章讲解过。这篇就到这里,下一篇我们来完善一下这个openfeign,使其可以应用在生产环境上。
本文代码下载:点击下载
还没有评论,来说两句吧...