Feign的理解


Feign是什么?

Feign是一個http請求調用的輕量級框架,也可以說是聲明式WebService客戶端

Feign的作用

可以以Java接口注解的方式調用Http請求,它使java調用Http請求變的簡單
Feign集成了Ribbon,實現了客戶端的負載均衡

Feign的工作原理(簡易版)

1、首先通過@EnableFeignCleints注解開啟FeignCleint
2、根據Feign的規則實現接口,並加@FeignCleint注解
3、程序啟動后,會進行包掃描,掃描所有的@FeignCleint的注解的類,並將這些信息注入到ioc容器中。
4、當接口的方法被調用,通過jdk的代理,來生成具體的RequesTemplate
5、RequesTemplate再生成Request
6、Request交給Client去處理,其中Client默認是HttpUrlConnection(也可以是HttpClient或Okhttp,需要配置)
7、最后Client被封裝到LoadBalanceClient類,這個類結合類Ribbon做到了負載均衡。

啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableHystrix
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class JisServiceConsumerApplication {

public static void main(String[] args) {
	SpringApplication.run(JisServiceConsumerApplication.class, args);
}

}

根據Feign的規則實現的接口

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableHystrix
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class JisServiceConsumerApplication {

public static void main(String[] args) {
	SpringApplication.run(JisServiceConsumerApplication.class, args);
}

}

熔斷器的fallback(調用接口失敗時會執行)

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.jisserviceconsumer.inter.HelloRemote;

@Component
public class HelloRemoteHystrix implements HelloRemote{

@Override
public String hello(@RequestParam(value = "name") String name) {
    return "hello" +name+", this messge send failed biu biu biu ~ ";
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM