简介
前面我们已经使用过了:
1、使用restTemplete调取其他微服务接口
2、使用ribbon实现服务中调用负载均衡
3、使用Hystrix实现服务中接口调用的失败保护措施
下面我来看看Fegin
Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。
同时fegin整合了ribbon和Hystrix,让我们不用单独配置两者,简化相关操作
Fegin具有以下特性:
1、可插拔的注解支持,包括Feign注解和JAX-RS注解;
2、支持可插拔的HTTP编码器和解码器;
3、支持Hystrix和它的Fallback;
4、支持Ribbon的负载均衡;
5、支持HTTP请求和响应的压缩。
开始搭建
第一步引入依赖加上注解
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类加上相关注解@EnableFeignClients
@SpringBootApplication
@EnableEurekaClient
//指定使用自己的负载均衡方式
//name为调用某个服务的时候使用自定义的负载均衡方式
//configuration为自定义负载均衡方式类
//@RibbonClient(name = "CLIENT2-SERVICE",configuration = MyRule.class)
//@EnableHystrix
@EnableFeignClients
public class Client1ServerApplication {
public static void main(String[] args) {
SpringApplication.run(Client1ServerApplication.class, args);
}
}
第二步写代码
创建相关接口
package org.example.fegin;
import org.example.feginCallback.DomeFeginCallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "CLIENT2-SERVICE", fallbackFactory = DomeFeginCallback.class)
@Service
public interface DomeFegin {
@GetMapping("client2/get")
String get(@RequestParam(name = "userId") String userId);
}
package org.example.feginCallback;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.example.fegin.DomeFegin;
import org.springframework.stereotype.Component;
/**
* @author shock wave 2
* @version 1.0
* @description: TODO
* @date 2021/6/1 15:45
*/
@Component
@Slf4j
public class DomeFeginCallback implements FallbackFactory<DomeFegin> {
@Override
public DomeFegin create(Throwable throwable) {
return new DomeFegin() {
@Override
public String get(String userId) {
return "小伙子,进入熔断了";
}
};
}
}
测试方法
@GetMapping("/getOther1")
public String getOther1(@RequestParam(required = false) String userId){
//Thread.sleep(3000);
return domeFegin.get(userId);
}
调用getOther1方法,成功返回
负载均衡配置
Fegin本身已经整合了ribbon,所以我们直接只用ribbon章节的相关配置即可,调用接口结果如下: 第一次:
第二次:
熔断器配置
Fegin同样整合了hystrix,我们直接使用yml配置的方式配置:
#开启fegin熔断器配置
feign:
hystrix:
enabled: true
#熔断器相关配置
hystrix:
command:
default:
execution:
isolation:
thread:
# 配置熔断器的超时时间,我这里配置了2s
timeoutInMilliseconds: 2000
开始测试
分别在client2和client3服务的get上面休眠3秒
@SneakyThrows
@GetMapping("/get")
public String get(@RequestParam(required = false) String userId, HttpServletRequest request){
Thread.sleep(3000);
return " From Port : " + request.getServerPort() + " , hello ";
}
调用getOther1接口,发现成功进入熔断
其他
fegin相关的其他配置
feign:
compression:
request:
# 开启请求压缩功能
enabled: true
#设置压缩的数据类型,此处也是默认值
mime-types: text/html,application/xml,application/json
# 设置什么时候触发压缩,当大小超过2048的时候
min-request-size: 2048
# 开启响应压缩功能
response:
enabled: true
调整日志级别
#Feign日志只会对日志级别为debug的做出响应
logging:
level: