一、前言
1、 此篇博客主要记录自己最近尝试使用feign调用三方项目的接口而编辑的demo,不足之处,烦请指点一二!!!!
2、分别搭建用户中心(eureka)、服务提供方(server)、客户端(client),如下图:
二、搭建用户中心
1、pom文件(eureka.pom):添加如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2、启动类上添加如下注解:
@EnableEurekaServer
如下图:
3、编辑配置文件(application.yml)
如下图:
4、启动用户中心:
访问地址(此处是本篇博客使用地址):http://localhost:9999/
如下图:
以上用户中心搭建完毕!!!!
三、搭建服务提供端(service)
1、pom文件(service.pom):添加如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2、启动类上添加如下注解:
@EnableDiscoveryClient
如下图:
3、编辑配置文件(application.yml):
如下图:
4、编辑对外提供服务的接口(如下示例):
a、service结构如下:
b、编辑ServiceApi,如下图:
c、编辑ServiceController,如下图:
5、启动server服务(注:要保证eureka注册中心是启动状态):
如下图:
如上:服务端配置完成!!!
四、搭建客户端(client):
1、pom文件(client.pom),添加如下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
以上依赖多了个spring-cloud-starter-openfeign,是为了开启feign调用
2、启动类上添加如下注解:
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.client.api")
如下图:
3、编辑配置文件(application.yml):
如下图:
4、编辑调用服务端(service)的接口:
a、client结构如下:
b、编辑ClientApi,如下图:
注:此处编辑feignClient接口注意事项比较多:
1、包括参数注解需要指定value,
2、请求注解只能用@RequestMapping,自己定义请求method,
3、如果是post请求,里面的RequestBody性质的参数只能有一个
4、特别注意调用路径问题,否则会出现404的错误
c、编辑ClientController,如下图:
5、启动客户端(保证注册中心eureka和服务端service已经启动):
如下图:
以上客户端搭建完毕!!!
五、校验客户端是否能够通过feign调用服务端提供的接口
1、请求路径:
http://localhost:7777/api/client/findName?name=zgl
2、请求结果:
3、也可以在服务端打一个断点,然后调用客户端的接口,看服务端的断点是否可以拦截,如下图:
综上就是通过feign调用三方接口的一个demo!!!!