1、概述
Spring Cloud OpenFeign
实现了声明式的http调用,并集成Ribbon,提供负载均衡的功能,整合 Hystrix
,提供服务容错能力。
2、环境准备
order-service去调用product-service,
在product-service
有一个Controller,order-service
去调这个服务
@RestController
@RequestMapping("/api/v1/product")
public class ProductController {
/**
* 根据id查找商品详情
* @param id
* @return
*/
@RequestMapping("find")
public String findById(@RequestParam("id") int id){
System.out.println("product id: " + id);
return "iPhone X";
}
}
现在搭建order-service
3、order-service
3.1、依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
3.2、配置文件
server:
port: 8090
#指定注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:7001/eureka/
#服务的名称
spring:
application:
name: order-service
3.3、启动类
加上@EnableFeignClients
注解
@EnableFeignClients
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3.4、ProductClient
@FeignClient(name = "product-service")
public interface ProductClient {
@GetMapping("/api/v1/product/find")
String findById(@RequestParam(value = "id") int id);
}
3.5、OrderController
@RestController
@RequestMapping("api/v1/order")
public class OrderController {
@Autowired
ProductClient productClient;
@RequestMapping("save")
public String save(@RequestParam("product_id") int productId){
// 调用feign接口
return productClient.findById(productId);
}
}
3.6、测试
4、feign的默认配置
FeignClientProperties.java
下的FeignClientConfiguration
public static class FeignClientConfiguration {
// Feign 日志级别。默认为 NONE
private Level loggerLevel;
// 请求的连接超时时长,单位:毫秒。默认为 10 * 1000 毫秒
private Integer connectTimeout;
// 请求的读取超时时长,单位:毫秒。默认为 60 * 1000 毫秒
private Integer readTimeout;
// 重试策略。默认为不重试
private Class<Retryer> retryer;
private Class<ErrorDecoder> errorDecoder;
private List<Class<RequestInterceptor>> requestInterceptors;
private Boolean decode404;
private Class<Decoder> decoder;
private Class<Encoder> encoder;
private Class<Contract> contract;
private ExceptionPropagationPolicy exceptionPropagationPolicy;
...
}
自定义配置:如
feign:
client:
config:
default:
connectTimeout: 1000
readTimeout: 1000
5、单独使用
如果服务的提供者和服务的调用者不在同一个注册中心
@FeignClient(name = "localhost", url="http://localhost:8081") //name和url的host要相同
public interface ProductClient {
@GetMapping("/api/v1/product/find")
String findById(@RequestParam("id") int id);
}