1. 简介
Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.
- Feign 是一个声明式调用HTTP协议服务的客户端
- 支持注解形式发现与调用服务
- 支持编码与解码
- 与Ribbon、Eureka结合使用可实现负载均衡功能
2. 代码实现
2.1涉及的模块
- eureka-server-singleton:服务注册中心,端口8761
- eureka-service: 服务提供者,通过profile指定不同端口模拟一组微服务,端口8762、8763
- eureka-service-feign:通过Feign调用服务提供者提供的服务
2.2 源代码
2.2.1 Github地址
https://github.com/andyChenHuaYing/spring-cloud-demo
2.2.2 切换
通过tag切换git tag -d v1.0,若想修改,可根据此tag创建新的分支。
2.3 eureka-server-singleton
与Spring Cloud 之服务发现与调用-Ribbon#2.3 eureka-server-singleton 没有任何区别
2.4 eureka-service
2.5 eureka-service-feign
2.5.1整体实现步骤
- pom.xml中引入
spring-cloud-starter-netflix-eureka-server
和spring-cloud-starter-openfeign
依赖 - application.yml中指定配置项,端口、application.name、eureka-server地址
- SpringBoot 启动类添加启用Fegin的注解
@EnableFeignClients
- 在当前项目Service接口类名上使用FeignClient注解指定服务提供者的服务名
@FeignClient("eureka-service")
- 在需要调用服务提供者的接口方法之上使用注解指定调用服务提供者提供的方法
@RequestMapping("/print")
- 在需要使用服务提供者提供的方法之处,使用第4步与第5步实例化好的服务提供者的方法
2.5.2 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-finchley-demo</artifactId>
<groupId>org.oscar.scd</g