Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
简而言之:
- Feign 采用的是基于接口的注解
- Feign 整合了ribbon
新建一个spring-boot工程,取名为serice-feign,在它的pom文件引入Feign的起步依赖spring-cloud-starter-feign、Eureka的起步依赖spring-cloud-starter-eureka、Web的起步依赖spring-boot-starter-web
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ server.port=8765 spring.application.name=client-feign
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class ClientfeignApplication { public static void main(String[] args) { SpringApplication.run(ClientfeignApplication.class, args); } }
定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了service-hi服务的“/hi”接口,代码如下:
@FeignClient(value = "service-hi") public interface SchedualServiceHi { @RequestMapping(value = "/hi",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
定义controller
@RestController public class HiController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired SchedualServiceHi schedualServiceHi; @RequestMapping(value = "/hi") public String sayHi(@RequestParam String name){ logger.info("feign ====> "+name); return schedualServiceHi.sayHiFromClientOne(name); } }