Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。 简而言之:
启动上篇中Eureka演示工程中Eureka Server与Eureka Client Provider服务 并在Eureka Client Provider中Controller增加一个接口用于Feign调用测试
@RestController @RequestMapping("/demo") public class DemoController { @Value("${server.port:#{null}}") private String serverPort; @GetMapping("/hello") public String hello() { return "Hello " + serverPort; } @GetMapping("/feign") public String feignTest(@RequestParam(value = "name") String name){ return "Hello Feign "+ name; } } 复制代码
新建一个maven工程,取名为:spring-cloud-feign-demo,添加如下依赖pom.xml中
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-demo</artifactId> <groupId>com.hxmec</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>spring-cloud-feign-demo</artifactId> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies> </project> 复制代码
新建application.yml,增加下面的配置
server: port: 9003 spring: application: name: feign-demo logging: pattern: console: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n' eureka: client: service-url: defaultZone: http://localhost:8888/eureka/ 复制代码
创建一个启动类 FeignDemoApplication,添加Feign相关注解
@SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient @EnableFeignClients public class FeignDemoApplication { public static void main(String[] args) { SpringApplication.run(FeignDemoApplication.class, args ); } } 复制代码
编写Feign接口服务
@FeignClient(value = "eureka-client-provider")//此名称为消费提供者注册的服务名称 public interface FeignService { @RequestMapping(value = "/demo/feign",method = RequestMethod.GET) String feignTest(@RequestParam(value = "name") String name); } 复制代码
编写Controller层调用Feign接口实例
@RestController @RequestMapping("/feign") @AllArgsConstructor public class FeignClientController { private final FeignService feignService; @GetMapping(value = "/test1") public String feign(@RequestParam String name) { return feignService.feignTest(name); } } 复制代码
启动项目,打开http://localhost:8888可以看到应用已经注册到Eureka注册中心
请求http://localhost:9003/feign/test1?name=Trazen验证是否成功调用服务提供者接口