基于 Ribbon 与 OpenFeign 的微服务间调用

目标:在微服务 A 中调用微服务 B 中的接口

  1. 添加 Ribbon 与 OpenFeign 的依赖
    (1)由于 nacos-discovery 已包含了 Ribbon,因此无需引入该依赖
    (2)但从 2022.0.1 版本的 Spring Cloud 开始,需要引入 loadbalancer 才能使用 LoadBalanced 的注解
    (3)因此只需要单独引入 OpenFeign 的依赖

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  2. 创建 RestTemplate 配置类,将 RestTempleate 纳入 Spring 管理,才能实现自动注入 Autowire

    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    /**
    * RibbonConfig
    */
    @Configuration
    public class RibbonConfig {
    
       @Bean
       @LoadBalanced
       public RestTemplate restTemplate(){
          return new RestTemplate();
       }
    }
    
  3. 在 Application 启动类中启用 Feign 的注解

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    
    @SpringBootApplication
    @EnableFeignClients
    public class AServiceApplication {
       public static void main(String[] args) {
          SpringApplication.run(AServiceApplication.class, args);
       }
    }
    
  4. 创建一个 Service 接口,用于调用微服务 B 的接口

    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    
    import com.example.entity.SampleObject;
    
    @FeignClient(value="b-service")
    public interface BServiceService {
    
       @GetMapping("/sample")
       SampleObject getSampleObject();
    }
    
  5. 在 Controller 类接口中调用该服务的接口

    
     @Autowired
     BServiceService bServiceService;
    
     @GetMapping("sampleobj")
     public SampleObject getSampleObject() {
         return bServiceService.getSampleObject();
     }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值