1.服务消费者pom.xml文件引入依赖
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
此处用的openFeign,为springCloud对feign的封装,加了对springMvc注解的支持
2.启动类加上@EnableFeignClients注解
@SpringBootApplication
@EnableFeignClients
public class AutoApplication9001 {
public static void main(String[] args) {
SpringApplication.run(AutoApplication9001.class,args);
}
}
3.添加接口,面向接口编程,接口方法是服务提供方提供的接口方法
@FeignClient(name = "find",fallback = CallBackImpl.class,path = "/resume")
//@RequestMapping("/resume")
public interface FindService {
@GetMapping("/openstate/{userId}")
Integer findOneById(@PathVariable("userId") Long userId);
}
4.回退方法类,定义回退方法要开启hystrix
import org.springframework.stereotype.Component;
@Component
public class CallBackImpl implements FindService{
@Override
public Integer findOneById(Long userId) {
return -6;
}
}
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 9000
5.Fegin默认请求处理超时时长1s,可以配置ribbon,会以ribbon的为准
find:
ribbon:
#请求连接超时时间
ConnectTimeout: 2000
#请求处理超时时间
ReadTimeout: 15000
#对所有操作都进⾏重试
OkToRetryOnAllOperations: true
MaxAutoRetries: 0 #对当前选中实例重试次数,不包括第⼀次调⽤
MaxAutoRetriesNextServer: 0 #切换实例的重试次数
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #负载策略调整
6.Ribbon和Hystrix的请求超时时长都设置了,以最小的为准
7.Feign对请求压缩和响应压缩的支持
feign:
compression:
request:
enabled: true
mime-types: text/html,application/xml,application/json # 设置压缩的数据类型,此处也是默认值
min-request-size: 2048 # 设置触发压缩的⼤⼩下限,此处也是默认值
response:
enabled: true
8.Feign日志级别设置
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLevel() {
return Logger.Level.FULL;
}
}
logging:
level:
# Feign⽇志只会对⽇志级别为debug的做出响应
controller.service.feginService: debug