Spring Cloud Alibaba-OpenFign实现服务调用

本文介绍了OpenFeign在Spring Cloud中的作用,它作为一个声明式的HTTP客户端,简化了远程服务调用。当与Nacos结合时,OpenFeign默认集成了Ribbon,从而实现负载均衡。通过引入依赖、启用注解、定义Feign接口以及修改Controller代码,可以轻松完成OpenFeign的配置和使用,让服务间的调用变得简单直接。

一、什么是OpenFeign

        OpenFeignSpring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。

        Nacos很好的兼容了Feign Feign负载均衡默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。

二、OpenFeign的使用

1.导入openfeign的依赖

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

2.在主启动类上开启OpenFeign注解

@EnableFeignClients//开启openfeign注解

3.创建feign的接口

package com.gsh.order.feign;

import com.gsh.util.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "springcloud-product")//被调用的微服务的名称
public interface ProductFeign {
    //被调用的方法
    @GetMapping("/product/findById/{pid}")
    public CommonResult findById(@PathVariable Integer pid);
}

4.修改controller代码

(1)注入feign接口

@Autowired
    private ProductFeign productFeign;

(2)使用注入的feign调用接口中的方法

        //这里直接使用productFeign调用接口中的方法,和我们原来controller调用service一样啊
        CommonResult byId = productFeign.findById(pid);
        JSONObject jsonObject=JSONObject.fromObject(byId.getData());
        System.out.println(jsonObject);
        Product product = (Product) JSONObject.toBean(jsonObject, Product.class);

5.重启服务即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值