概述
什么是Feign?与 Ribbon ⼀样,Feign 也是由 Netflflix 提供的,Feign 是⼀个声明式、模版化的 Web Service 客户端,它简化了开发者编写 Web 服务客户端的操作,开发者可以通过简单的接⼝和注解来调⽤ HTTP API, Spring Cloud Feign,它整合了 Ribbon 和 Hystrix,具有可插拔、基于注解、负载均衡、服务熔断等⼀系列便捷功能。
特点
(1)Feign 是⼀个声明式的 Web Service 客户端;
(2)⽀持 Feign 注解、Spring MVC 注解、JAX-RS 注解;
(3)Feign 基于 Ribbon 实现,使⽤起来更加简单;
(4)Feign 集成了 Hystrix,具备服务熔断降级的功能。
示例
1.首先创建服务端项目,提供数据接口。
编辑
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> </dependencies>
application.yaml
server: port: 8081 servlet: context-path: /api/server spring: application: name: userService
User
@Data public class User { private Long id; private String name; private Integer age; }
UserController
@RestController public class UserController { @GetMapping("/getUserInfo") public User getUserInfo(){ User user = new User(); user.setId(1L); user.setName("BanQ"); user.setAge(21); return user; } }
启动类
@SpringBootApplication public class ServerApplication { public static void main(String[] args) { SpringApplication.run(ServerApplication.class,args); } }
浏览器访问:http://localhost:8081/api/server/getUserInfo
编辑
2.创建客户端项目,调用服务端接口。
编辑
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.0.2.RELEASE</version> </dependency> </dependencies>
application.yaml
server: port: 8082 servlet: context-path: /api/client
UserFeignClient
@FeignClient( name = "userService", url = "http://localhost:8081/api/server" ) public interface UserFeignClient { @RequestMapping(value = "/getUserInfo",method = RequestMethod.GET) @ResponseBody String getUserInfo(); }
TestController
@RestController public class TestController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/get") public String get(){ return userFeignClient.getUserInfo(); } }
启动类
@EnableFeignClients @SpringBootApplication public class ClientApplication { public static void main(String[] args) { SpringApplication.run(ClientApplication.class,args); } }
浏览器访问:http://localhost:8082/api/client/get
编辑
这样就实现了通过feign client来调用远程(第三方)接口了。