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客户端创建的动态代理。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zxg45

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值