OpenFeign简单使用

1. 声明式 REST 客户端:Feign

Feign是一个声明式 Web 服务客户端。它使编写 Web 服务客户端变得更容易。要使用 Feign 创建一个接口并对其进行注释。它具有可插入的注释支持,包括 Feign 注释和 JAX-RS 注释。Feign 还支持可插拔的编码器和解码器。Spring Cloud 添加了对 Spring MVC 注解的支持,并支持使用HttpMessageConvertersSpring Web 中默认使用的注解Spring Cloud 集成了 Eureka、Spring Cloud CircuitBreaker 和 Spring Cloud LoadBalancer,在使用 Feign 时提供负载均衡的 http 客户端。

官网地址

2.简单使用

2.1主启动类

@SpringBootApplication
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

2.2服务提供者Controller代码

@GetMapping("/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
Payment payment = paymentService.getPaymentById(id);
log.info("输出的信息:" + payment);
if(payment != null){
return new CommonResult(200,"成功,serverPort:"+ serverPort,payment);
}else {
return new CommonResult(444,"没有对应记录,查询ID"+id,null);
}
}

2.3服务消费者service代码

import com.fly.springcloud.entity.CommonResult;
import com.fly.springcloud.entity.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author 26414
 */
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {

  @GetMapping(value = "/payment/get/{id}")
  CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);


}

2.4服务消费者Controller代码

import javax.annotation.Resource;

/**
 * @author 26414
 */
@RestController
@Slf4j
public class OrderFeignController {

  @Resource
  private PaymentFeignService paymentFeignService;

  @GetMapping(value = "/consumer/payment/get/{id}")
  public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
    return paymentFeignService.getPaymentById(id);
  }

}

3.超时控制

feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic

4.日志

应用程序.yml

logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.fly.springcloud.service.PaymentFeignService: debug

前面的名称是用于创建 Feign 客户端的接口的完整类名。

Logger.Level您可以为每个客户端配置的对象告诉 Feign 要记录多少。选择是:

  • NONE,无日志记录(默认)。

  • BASIC, 只记录请求方法和 URL 以及响应状态码和执行时间。

  • HEADERS, 记录基本信息以及请求和响应标头。

  • FULL, 记录请求和响应的标头、正文和元数据。

@Configuration
public class FooConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

 

OpenFeign简单使用

上一篇:vue开发个性化select,带分页以及搜索功能的组件


下一篇:Hard | LeetCode 84. 柱状图中最大的矩形 | 单调栈