Feign和Ribbon的区别,Feign的使用和相关配置
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.链接: 参考资料.