feign简易使用步骤
Feign暴露服务步骤
将希望提供出去,给别人调用的服务,在api服务中声名rest接口,供别人调用
首先可能是父子工程(如 auth下有auth-pojo、auth-service)
1.新建一个auth-api 子工程用于向外提供rest接口
然后导入依赖
<!--feign的核心依赖即可-->
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
</dependency>
<!--pojo很可能会用到,也可以用作 依赖传递-->
<dependency>
<groupId>com.xxx</groupId>
<artifactId>xxx-pojo</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
2.工厂目录下建包,路径随意,规范优先
然后创建接口
@FeignClient("被调用的服务名称") //feign客户端注解
public interface XxxClient {
@GetMapping("/rest一级目录/rest二级目录") //目录注意一定要能匹配上
String getSecretKey( //下面是方法实例,从controller拷贝过来的
@RequestParam("clientId") String clientId,
@RequestParam("secret") String secret);
}
然后就是服务调用端了
1.依赖
<!--提供rest接口的工程 api 的依赖-->
<dependency>
<groupId>com.xxx</groupId>
<artifactId>xxx-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!--feign的启动类依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.启动类加 启动feign注解
@EnableFeignClients
public class XxxApplication {
...
}
3.在需要调用的地方直接 注入
@Autowired
private XxxClient xxxClient;//rest接口
调用方法即可
因为依赖了提供rest接口的依赖,所以XxxClient是此依赖工程中的
唯有努力,人生没有白走的路,每一步都算数