目录
前言
小伙伴们大家好,现在随着微服务的普遍化,项目中很多要用到远程服务的接口,通过以往的方式RestTemplate调用的话,格式较为复杂且可读性差,OpenFeign是一个声明式的http客户端,可以优雅的实现http请求的发送,解决上面的问题
实现方式
1.引入依赖---注意与springboot的版本关系
我这里的父级配置如下,使用的openfeign版本如下
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
2.添加注解 @EnableFeignClients
在需要调用远程服务项目的启动类上加上该注解开启OpenFeign功能
3.编写Feign客户端
这里调用的是另外一个本地项目的测试接口,调用成功会获得一个字符串提示
@FeignClient注解参数信息如下:
服务名称:demo-test (可以自定义)
请求方式:GET公共路径:http://localhost:8088/hello
请求路径:/getFeignTest
返回值类型:String
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author ben.huang
*/
@Component
@FeignClient(name = "demo-test",url = "http://localhost:8088/hello")
public interface FeignConnect {
@GetMapping("/getFeignTest")
String getTestFeign();
}
4.接口测试
测试接口就简单获取下结果并打印,测试结果如下,可以看到正确的获取了远程接口的返回结果
补充
1.带有参数的方法调用
带有请求参数的调用样式如下 ,就跟正常调用接口需要什么传什么,请求体/请求参数/请求头等
@GetMapping("/getFeignTest")
String getTestFeign(@RequestBody User user,@RequestHeader("token") String token ...);
2. 设置超时时间
这里设置了10s,测试下,在提供远程接口的方法上加个断点模拟下超时情景,结果如下,异常提示信息如下
feign:
client:
config:
default:
connectTimeout: 10000
readTimeout: 10000
2024-03-21 15:58:50.771 ERROR 17648 --- [nio-8079-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/fms] threw exception [Request processing failed; nested exception is feign.RetryableException: Read timed out executing GET http://localhost:8088/hello/getFeignTest] with root cause
3. 整合Hystrix实现熔断降级
Hystrix的作用
- 通过第三方客户端库访问(通常通过网络)的依赖项,提供对延迟和故障的保护和控制。
- 解决复杂分布式系统中的级联故障。
- 快速失败并快速恢复。
- 在可能的情况下回退并优雅地降级。
- 实现近乎实时的监控、警报和操作控制。
3.1 引入Hystrix依赖,配置依赖,重写方法,然后在@FeignClient中指定fallback
属性为实现类即可,发生熔断时,会返回实现类方法中的返回值
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
import org.springframework.stereotype.Component;
@Component
public class FeignFallBack implements FeignConnect{
@Override
public String getTestFeign() {
System.out.println("!!! error --_--");
return "error --_--'";
}
}
3.2 测试下,依然是提供远程的接口打断点模拟超时
章末
好了,文章到这里就结束了~