一、Feign简介
Feign是一个声明式的伪Http客户端。具有可插拔的注解支持,包括Feign注解和JAX-RS注解。它在Netflix Feign的基础上扩展了对Spring MVC的注解支持。Feign支持可插拔的编码器和解码器,默认集成Ribbon,和Eureka结合,默认实现负载均衡。
二、创建Feign服务
pom文件依赖如下:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
application.properties配置:
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ spring.application.name=hello-service-feign server.port=8763
在启动类添加注解,开启feign功能,如下:
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class HelloServiceFeignApplication { public static void main(String[] args) { SpringApplication.run(HelloServiceFeignApplication.class, args); } }
定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。
@FeignClient(value="hello-service") public interface HelloServiceFeign { @RequestMapping(value = "/hi",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
编写controller如下:
@RestController public class HelloController { @Autowired HelloServiceFeign helloServiceFeign; @RequestMapping(value = "/hi",method = RequestMethod.GET) public String sayHello(@RequestParam String name){ return helloServiceFeign.sayHiFromClientOne(name); } }
启动程序,访问http://localhost:8763/hi?name=zhao 出现以下:
hi zhao,i am from port:8082
证明已经完成。