Feign是一个声明式的伪Http客户端,它使得 Http 客户端编码变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和 JAX-RS 注解。Feign 支持可插拔的编码器和解码器。Feign 默认集成了 Ribbon,自然就实现了负载均衡的效果。
spring-cloud.s04.store-feign
在 pom
中添加依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <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.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies>
添加配置文件
application.yml
server: port: 31002 spring: application: name: store-feign eureka: client: serviceUrl: defaultZone: http://user:123123@localhost:34001/eureka/ instance: instance-id: ${spring.cloud.client.ip-address}:${server.port}/${spring.application.name} prefer-ip-address: true lease-renewal-interval-in-seconds: 10 lease-expiration-duration-in-seconds: 30
创建启动类 ..StoreFeign
@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class StoreFeign { public static void main(String[] args) { SpringApplication.run(StoreFeign.class, args); } }
为了专注 Feign 的使用,将 Feign 的应用提取到 service 层,与 controller 层的注解分开。创建 接口
..StoreFeignService
/* @FeignClient("") 参数填 Spring Cloud Provider 的应用名 ${spring.application.name} */ @FeignClient("album-provider") public interface StoreFeignService { /* @RequestMapping() 默认参数是请求资源的地址, 也可以指定请求的 Http Method @RequestMapping(value="/movie/movies",method=RequestMethod.GET) getMovies() 也可以算入参数,例如 getMovies(@RequestParam("name") String name) ,调用时比如传入的参数 */ @RequestMapping("/album/server-port") public String getProviderPort(); }
创建访问入口 ..StoreFeignController
@RestController @RequestMapping("/store-feign") public class StoreFeignController { @Autowired StoreFeignService storeFeignService; @RequestMapping("/album-provider-port") public String getProviderPort() { return storeFeignService.getProviderPort(); } }
http://localhost:31002/store-feign/album-provider-port
,多次刷新,可以发现负载均衡策略是轮训。 Feign 就是使用 Ribbon 的负载均衡策略,当然改变负载均衡策略的方法就与 Ribbon 的方法相同。