在使用Spring Cloud開發微服務應用時中,各個微服務服務提供者都是以HTTP接口的形式對外提供服務,因此服務消費者在調用服務提供者時,通過HTTP Client的方式訪問。當然我們可以使用JDK原生的`URLConnection`、`Apache的Http Client`、`Netty的異步HTTP Client`, Spring的`RestTemplate`去實現服務間的調用。Spring Cloud對Fegin進行了增強,使Fegin支持了Spring MVC的注解,並整合了Ribbon和Eureka,從而讓Fegin的使用更加方便(在Spring Cloud中使用Feign, 我們可以做到使用HTTP請求遠程服務時能與調用本地方法一樣的編碼體驗)。
一、FeignClient工作原理
總結來說,Feign的源碼實現的過程如下:
- 首先通過@EnableFeignCleints注解開啟FeignCleint
- 根據Feign的規則實現接口,並加@FeignCleint注解
- 程序啟動后,會進行包掃描,掃描所有的@ FeignCleint的注解的類,並將這些信息注入到ioc容器中
- 當接口的方法被調用,通過jdk的代理,來生成具體的RequesTemplate
- RequesTemplate在生成Request
- Request交給Client去處理,其中Client可以是HttpUrlConnection、HttpClient也可以是Okhttp
- 最后Client被封裝到LoadBalanceClient類,這個類結合類Ribbon做到了負載均衡
工作原理參見:https://zhuanlan.zhihu.com/p/28593019
二、示例
FeignClient相當於Spring Cloud中的RPC,使用示例如下:
(1)Eureka-Server注冊中心
application.yml配置如下:
#application.yml
server:
port: 1111
spring:
application:
name:eureka-server
eureka:
client:
register-with-eureka: false
fetch-registry: false
server-url:
defaultZone: http://localhost:${server.port}/eureka/
EurekaServerApplication配置如下:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class,args)
}
}
(2)Eureka-Producer配置
定義遠程服務HelloController
@RestController
public class HelloController {
@GetMapping("/hello")
public String xxx(@RequstParam String name) {
return "hello" + name + ", I'm eureka producer service!";
}
}
Eureka-Client中application.yml配置
server:
port: 1112
spring:
application:
name: eureka-producer
eureka:
client:
server-url:
defaultZone: http://localhost:1111/eureka/
EurekaProducerApplication
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaProducerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaProducerApplication.class,args)
}
}
(3)Eureka-Consumer配置
Controller層服務配置如下:
@RestController
public class ConsumerController {
@Autowired
HelloRemote helloRemote;
@RequestMapping("/hello/{name}")
public String hello(@PathVariable("name") String name) {
return helloRemote.hello(name);
}
}
HelloRemote配置
@FeignClient(name="eureka-producer")
public interface HelloRemote {
@RequstMapping("/hello")
String hello(@RequstParam(value="name") String name);
}
application.yml文件配置
server:
port: 1113
spring:
application:
name: eureka-consumer
eureka:
client:
server-url:
defaultZone: http://localhost:1111/eureka
EurekaConsumerApplication配置
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerApplication.class,args)
}
}
參見:http://www.voidcn.com/article/p-kodllxvn-hr.html
http://xujin.org/sc/sc-fegin01/
http://www.cnblogs.com/jalja/p/7011439.html
