一、Feign简介
Feign是Netflix开发的声明式、模版化的HTTP伪客户端。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
二、准备工作
继续用上一节的工程, 启动eureka-server,端口为1001; 启动user-service及user-service1服务,端口分别为8084、8085.
三、创建Feign服务器
新建一个feign-server服务器
pom代码如下:
4.0.0 com.example da-feign-server 0.0.1-SNAPSHOT jar da-feign-server Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.0.RELEASE UTF-8 UTF-8 1.8 Finchley.M8 org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
在工程的配置文件application.yml文件,指定程序名为feign-service,端口号为3001,服务注册地址为 ,代码如下:
eureka: client: serviceUrl: defaultZone: http://localhost:1001/eureka/ instance: lease-renewal-interval-in-seconds: 30server: port: 3001spring: application: name: feign-service
在程序的启动类DaFeignServerApplication,加上@EnableFeignClients注解开启Feign的功能:
@EnableFeignClients@EnableEurekaClient@SpringBootApplicationpublic class DaFeignServerApplication { public static void main(String[] args) { SpringApplication.run(DaFeignServerApplication.class, args); }}
定义一个feign接口,通过@FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了service-hi服务的“/hi”接口,代码如下:
@FeignClient(value = "user-service")public interface HiService { @RequestMapping(value = "/hi",method = RequestMethod.GET) String getHi(@RequestParam(value = "name") String name);}
controller层,对外暴露一个”/getHi”的API接口,通过上面定义的Feign客户端HiService来消费服务。代码如下:
@RestControllerpublic class HiController { @Autowired HiService hiService; @RequestMapping(value = "/getHi",method = RequestMethod.GET) public String getHi(@RequestParam String name){ return hiService.getHi(name); }}
启动程序,多次访问,浏览器交替显示:
四、源码下载
FeignServer源码下载: