Feign和Ribbon的区别,Feign的使用和相关配置

本文详细介绍了Spring Cloud中的Feign和Ribbon组件,它们都是用于服务调用,但Feign提供了更简洁的接口方式。通过创建Feign服务消费者,配置application.yml,启动类以及定义Feign接口,实现了服务调用。此外,还讨论了自定义Feign配置的注意事项,并给出了测试验证。文章最后总结了Feign相较于Ribbon的优势。
摘要由CSDN通过智能技术生成

LD is tigger forever,CG are not brothers forever, throw the pot and shine.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.

目录

概述

feign和ribbon是Spring Cloud的Netflix中提供的两个实现软负载均衡的组件,

Ribbon和Feign都是用于调用其他服务的,方式不同。

Feign则是在Ribbon的基础上进行了一次改进,采用接口的方式。

架构特性

设计思路

实现思路分析

新建Feign服务消费者

新建application.yml

server:
  port: 8084
  servlet:
    context-path: /springbootconsumer

spring:
  application:
    name: spring-boot-consumer-feign

eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8090/springcloudeureka/eureka/

2.4 新建Spring Boot启动类

这里要注意,启动类需增加类注解 @EnableFeignClients,表示此项目为Feign客户端



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SpringBootConsumerFeignApplication {

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

定义Feign接口

新建feign包,再新建GatewayFeignClient接口类。
@FeignClient(“服务id名称”),表示调用哪个服务@GetMapping(value = “接口地址”),表示调用哪个接口。这里要注意接口地址要保留server.servlet.context-path部分,没有则省略

新建控制器类

@RestController
@Scope("prototype")
public class GatewayController {

    @Autowired
    private GatewayFeignClient gatewayFeignClient;

    @GetMapping(value = "/gateway")
    public String gateway() throws Exception {
        return gatewayFeignClient.gateway();
    }
}

test测试

依次启动spring-cloud-eureka,spring-boot-provider,spring-boot-provider-v2,spring-boot-consumer-feign。然后浏览器访问http://127.0.0.1:8084/springbootconsumer/gateway,不断刷新,可以到到返回信息正常

自定义Feign配置

上篇我们自定义Ribbon负载均衡策略时,会出现包扫描的问题,Feign自定义配置也同样存在这个问题,这里我们不再赘述,直接使用注解 @ComponentScan 自定义扫描类。但是与上篇不同,我们这里自定义一个注解,当Java类使用了该注解时,@ComponentScan就会忽略扫描。

拓展实现

相关工具如下:

实验效果:(解决思路)

分析:

小结:

主要讲述了一些Ribbon里面有许多不足,请大家指正~

参考资料和推荐阅读

1.链接: 参考资料.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

执于代码

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

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

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

打赏作者

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

抵扣说明:

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

余额充值