首页 > 技术文章 > Openfeign的简单使用

mc-74120 2020-09-11 16:46 原文

OpenFeign和RestTemplate类似,也是进行服务调用转发的工具,和RestTemplate不同的是,OpenFeign是基于接口和注解进行转发和调用的,比起RestTemplate更为简单和科学,且集成了Ribbon,也能进行负载均衡。

OpenFeign的使用:

1.引入依赖:

<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

 

 可以看出,openfeign集成了ribbon


2.yml配置:
server:
port: 81
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/
feign:
client:
config:
default:
ConnectTimeOut: 5000 #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间。如果超过5秒,报错
ReadTimeOut: 10000 #指的是建立连接后从服务器读取到可用资源所用的时间。

3.主启动类:
@SpringBootApplication
@EnableFeignClients //开启openfeign的使用
public class openfeignmain {
public static void main(String[] args) {
SpringApplication.run(openfeignmain.class,args);
}
}
4.编写服务器调用接口:
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")//要调用的服务名称
//将服务名称和调用的url进行自动拼接
public interface PaymentService {
@GetMapping("payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") long id);
@GetMapping("payment/feign/timeout")//调用的服务的url
public String PaymentOpenFeignTimeout();
}
5.调用服务:
@RestController
@Slf4j
public class OpenfeignController {
@Resource
private PaymentService paymentService;
@GetMapping("consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") long id){
return paymentService.getPaymentById(id);
}
@GetMapping("consumer/payment/feign/timeout")
public String paymentFeignTimeout(){
//客户端默认等待一秒钟
return paymentService.PaymentOpenFeignTimeout();
}
}


推荐阅读