OpenFeign 是一个基于 Ribbon 和 Hystrix 的 HTTP 客户端,可以简化 RESTful API 的调用。它支持多种 HTTP 协议,包括 HTTP/1.1、HTTP/2、WebSocket 等。OpenFeign 通过注解的方式定义接口,并自动生成对应的 Java 代码,使得开发者可以更加方便地进行接口开发。
在 Spring Cloud 中,服务之间的调用是通过 Ribbon 实现的。Ribbon 是一个负载均衡器,可以在多个服务实例之间进行负载均衡。当一个请求到达时,Ribbon 会根据一定的负载均衡策略选择合适的服务实例进行请求。如果出现故障或者超时等情况,Ribbon 会通过熔断器和容错机制来保护应用程序的稳定性。
Hystrix 是阿里巴巴开源的一个容错框架,可以在服务调用过程中提供熔断器、降级、限流等功能,从而保证服务的可靠性和稳定性。Hystrix 还提供了丰富的统计信息和监控功能,可以帮助开发者快速定位问题。
使用 OpenFeign 可以大大简化接口的开发过程,同时还可以享受到 Ribbon 和 Hystrix 带来的高可用性和稳定性。
官方文档
使用
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
</dependencies>
启动类注解
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
service
@Service
@FeignClient(value = "provider")
public interface TestService {
@RequestMapping("/dept/getDept")
String getDept();
}
controller
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/getDept")
public String getDept() {
return testService.getDept();
}
}
超时时间
#连接超时
feign.client.config.default.connect-timeout=5000
#读超时
feign.client.config.default.read-timeout=5000
自此项目整合完毕,在实际的项目中我们可以把上面的service放到一个公共模块供所有模块一起使用。
当然OpenFeign的还有很多配置,大家可以移步官网,官网描述比较详情。