Feign簡介
Feign是Neflix開發的輕量級restful的HTTP服務客戶端,是以Java接口註解方式調用HTTP請求。不需要我們拼接url通過調用restTemplate的api,只需要創建一個接口加上寫註解直接調用接口即可。
本質: 封裝http嗲用流程,更符合面向接口化編程的習慣,類似Dubbo的服務調用
Feign應用
基本配置
這裏創建兩個服務cloud-service-code
作爲消費者服務去遠程調用cloud-service-email
提供者服務
cloud-service-email提供者
1.controller中創建方法sendEmail()
用以消費者調用
@RestController
@RequestMapping("/email")
public class EmailController {
@PostMapping("/{email}/{code}")
public Boolean sendEmail(@PathVariable String email,@PathVariable String code) {
return true;
}
}
2.yml配置信息
server:
port: 8082
#註冊到Eureka服務中心
eureka:
client:
service-url:
# 註冊到集羣,就把多個Eurekaserver地址使用逗號連接起來即可;註冊到單實例(非集羣模式),那就寫一個就ok
defaultZone: http://EurekaServerA:8761/eureka,http://EurekaServerB:8762/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@
spring:
application:
name: cloud-service-email
management:
endpoints:
web:
exposure:
include: "*"
# 暴露健康接口的細節
endpoint:
health:
show-details: always
3.配置啓動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class EmailApplication {
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class,args);
}
}
cloud-service-code消費者
1.引入Feign依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
server:
port: 8081
#註冊到Eureka服務中心
eureka:
client:
service-url:
# 註冊到集羣,就把多個Eurekaserver地址使用逗號連接起來即可;註冊到單實例(非集羣模式),那就寫一個就ok
defaultZone: http://EurekaServerA:8761/eureka,http://EurekaServerB:8762/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@
spring:
application:
name: cloud-service-code
management:
endpoints:
web:
exposure:
include: "*"
# 暴露健康接口的細節
endpoint:
health:
show-details: always
2.服務消費者啓動類添加對Feign支持的註解@EnableFeignClients
該註解會同時支持hystrix所以不需要再添加hystrix註解@EnableCircuitBreaker
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 開啓Feign 客戶端功能
@EntityScan("com.cloud.pojo")
public class CodeApplication {
public static void main(String[] args) {
SpringApplication.run(CodeApplication.class,args);
}
}
3.創建Feign接口
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
// name:調⽤的服務名稱,和服務提供者yml⽂件中spring.application.name保持⼀致
@FeignClient(name= "cloud-service-email")
public interface EmailServiceFeignClient {
//調⽤的請求路徑(與cloud-service-email提供者的controller方法保持一致)
@PostMapping("/{email}/{code}")
public Boolean sendEmail(@PathVariable("email") String email, @PathVariable("code") String code);
}
4.在controller中直接就可以完成遠程調用
package com.cloud.controller;
import com.cloud.feign.EmailServiceFeignClient;
import com.cloud.service.CodeService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/code")
public class CodeController {
@Autowired
private EmailServiceFeignClient emailServiceFeignClient;
@PostMapping("/create/{email}")
public Boolean createCode(@PathVariable String email) {
String code = RandomStringUtils.randomAlphanumeric(6);
codeService.addCode(email, code);
Boolean result = emailServiceFeignClient.sendEmail(email, code);
return result;
}
}
負載均衡配置
Feign本身已經集成了Ribbon和Hystrix的依賴和自動配置,不需要再額外引入依賴,可用通過ribbon.xx
來進行全局配置,也可以服務名.ribbon.xx
來對指定服務進行配置
#針對的被調⽤⽅微服務名稱,不加就是全局⽣效
cloud-service-code:
ribbon:
#請求連接超時時間
#ConnectTimeout: 2000
#請求處理超時時間
#ReadTimeout: 5000
#對所有操作都進⾏重試
OkToRetryOnAllOperations: true
####根據如上配置,當訪問到故障請求的時候,它會再嘗試訪問⼀次當前實例(次數由MaxAutoRetries配置),
####如果不⾏,就換⼀個實例進⾏訪問,如果還不⾏,再換⼀次實例訪問(更換次數由MaxAutoRetriesNextServer配置),
####如果依然不⾏,返回失敗信息。
MaxAutoRetries: 0 #對當前選中實例重試次數,不包括第⼀次調⽤
MaxAutoRetriesNextServer: 0 #切換實例的重試次數
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #負載策略調整
熔斷器配置
1.啓用熔斷功能配置
# 開啓Feign的熔斷功能
feign:
hystrix:
enabled: true
其餘配置與Hystrix配置方式相同
由於兩個超時時間設置(Feign/Hystrix),熔斷的時候是根據這兩個時間的最小值進行
2.修改feign接口
/// 使⽤fallback的時候,類上的@RequestMapping的url前綴限定,改成配置在@FeignClient的path屬性中
@FeignClient(value = "cloud-service-email",fallback = EmailFallback.class,path = "/email")
public interface EmailServiceFeignClient {
@PostMapping("/{email}/{code}")
public Boolean sendEmail(@PathVariable("email") String email, @PathVariable("code") String code);
}
3.熔斷方法
降級回退邏輯需要定義⼀個類,實現FeignClient接⼝,實現接⼝中的⽅法
import org.springframework.stereotype.Component;
@Component
public class EmailFallback implements EmailServiceFeignClient{
@Override
public Boolean sendEmail(String email, String code) {
return false;
}
}
日誌配置
1.開啓Feign日誌功能及級別
// Feign的⽇志級別(Feign請求過程信息)
// NONE:默認的,不顯示任何⽇志----性能最好
// BASIC:僅記錄請求⽅法、URL、響應狀態碼以及執⾏時間----⽣產問題追蹤
// HEADERS:在BASIC級別的基礎上,記錄請求和響應的header
// FULL:記錄請求和響應的header、body和元數據----適⽤於開發及測試環境定位問題
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLevel() {
return Logger.Level.FULL;
}
}
2.配置log級別爲debug
logging:
level:
# Feign⽇志只會對⽇志級別爲debug的做出響應
com.cloud.feign.EmailServiceFeignClient: debug