Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
创建feign工程
引入相关依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <dependencies> <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> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies>
|
application.yml
1 2 3 4 5 6 7 8 9 10 11 12
| server: port: 8086
# 服务与服务之间相互调用一般都是根据这个name spring: application: name:feign-service
eureka: client: serviceUrl: defaultZone: http:
|
启动
1 2 3 4 5 6 7 8 9 10 11 12 13
| import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication @EnableFeignClients @EnableEurekaClient public class FeignServerApplication { public static void main(String[] args) { SpringApplication.run(FeignServerApplication.class,args); } }
|
声明一个interface接口
1 2 3 4 5 6 7 8 9 10 11
| import com.felix.project.config.FeignConfig; import com.felix.project.fallback.EurekaClientFeignHystric; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = "user-service") public interface EurekaClientFeign { @GetMapping(value = "/user/list") Object getList(); }
|
service 层
1 2 3 4 5 6 7 8
| @Service public class UserService { @Autowired private EurekaClientFeign eurekaClientFeign; public Object getList(){ return eurekaClientFeign.getList(); } }
|
controller调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import com.felix.project.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @GetMapping(value = "/list") public Object list(){ return userService.getList(); } }
|
请求
多次请求 http://localhost:8765/user/list 发现端口号相互交换,达到了负载均衡的作用。
效果与 SpringCloud之三Ribbon(负载均衡)结果一样