SpringCloud服务调用 OpenFeign

Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需 创建一个接口并在接口上添加注解即可。

OpenFeign 是Spring Cloud 在Feign 的基础上支持了SpringMVC 的注解,如@RequestMapping等。OpenFeign 的@FeignClient 可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。

Feign自带负载均衡配置项。

  1. 首先向注册中心注册微服务 cloud-payment-service
    测试类

    @GetMapping("/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
          
          
        Payment payment = paymentService.getPaymentById(id);
        log.info("*** 查询结果:" + payment);
    
        if (payment != null) {
          
          
            return new CommonResult<Payment>(200, "查询成功,server.port = "+serverPort, payment);
        } else {
          
          
            return new CommonResult<Payment>(444, ",没有对应记录,id=" + id, null);
        }
    }
    
  2. 注册消费微服务,使用服务调用 OpenFeign
    主程序

    @SpringBootApplication
    @EnableEurekaClient
    //激活feign
    @EnableFeignClients
    public class OrderFeignApplication81 {
          
          
        public static void main(String[] args) {
          
          
            SpringApplication.run(OrderFeignApplication81.class,args);
        }
    }
    

    service层

    @Component
    //指定微服务,Feign自带负载均衡配置项
    @FeignClient(value = "CLOUD-PAYMENT-SERVICE")
    public interface PaymentFeignService {
          
          
    
        //这个路径对应指定的微服务的路径
        @GetMapping("payment/get/{id}")
        public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
    }
    

    这个接口上方的路径对应指定的微服务CLOUD-PAYMENT-SERVICE下的路径。

    测试类controller

    @RestController
    @Slf4j
    public class OrderFeignController {
          
          
    
        @Resource
        private PaymentFeignService paymentFeignService;
    	
    	//调用service层接口
        @GetMapping("/consumer/payment/get/{id}")
        public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
          
          
            log.info("***consumer-feign-order       id="+id);
            return paymentFeignService.getPaymentById(id);
        }
    

本质就是服务消费者的service层接口直接映射服务提供者的接口

接口使用了注解@FeignClient,则客户端会针对这个接口创建一个动态代理。调用该接口,实质就是调用Feign客户端创建的动态代理。

猜你喜欢

转载自blog.csdn.net/Zhangxg0206/article/details/113965080