目录
一、什么是Ribbon
Ribbon是一个客户端负载均衡工具,通过Spring Cloud封装,可以轻松和AlibabaCloud整合
服务启动类下增加@LoadBalanced 注解
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
二、Ribbon调用
Video video = restTemplate.getForObject("http://wnn-video-service/api/v1/video/find_by_id?videoId="+videoId, Video.class);
第一次使用Ribbon进行客户端调用的时候,会出现接口超时,加上以下配置即可
#自定义ribbon的超时时间
ribbon:
ReadTimeout: 5000 #处理请求的超时时间,默认为5秒
ConnectTimeout: 5000 #连接建立的超时时长,默认5秒
MaxAutoRetries: 1 #同一台实例的最大重试次数,但是不包括首次调用,默认为1次
MaxAutoRetriesNextServer: 0 #重试负载均衡其他实例的最大重试次数,不包括首次调用,默认为0次
OkToRetryOnAllOperations: false #/是否对所有操作都重试,默认false
默认使用轮询的方式,调用对方接口。
三、什么是Feign
使用Ribbon带来的问题
Ribbon代码存在的问题:不规范,风格不统一,需要做参数拼接等维护性比较差.
SpringCloud提供的伪http客户端(本质还是用http),封装了Http调用流程,更适合面向接口化
让用Java接口注解的方式调用Http请求.
不用像Ribbon中通过封装HTTP请求报文的方式调用 Feign默认集成了Ribbon
官方文档
https://spring.io/projects/spring-cloud-openfeign
版本 2.2.5
Nacos支持Feign,可以直接集成实现负载均衡的效果
四、Feign的使用
使用feign会更加的解耦
引入依赖。版本不用指定是根据springcloud版本来的
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类增加注解
//开启Feign支持
@EnableFeignClients
增加一个service接口
其中:@FeignClient的value和nacos的名称保持一致
@FeignClient(value = "wnn-video-service")
public interface VideoService {
@GetMapping("/api/v1/video/find_by_id")
Video findById(@RequestParam("videoId") int videoId);
@PostMapping("/api/v1/video/save")
int save(@RequestBody Video video);
}
调用:
@Autowired private VideoService videoService; Video video = videoService.findById(videoId);//get方式
/**
* 测试 feign 调用 使用post方式传输对象
* @param video
* @return
*/
@RequestMapping("save")
public Object save(@RequestBody Video video){
Integer rows = videoService.save(video);
Map<String,Object> map = new HashMap<>();
map.put("rows",rows);
return map;
}
Ribbon和feign两个的区别和选择
选择feign
默认集成了ribbon
写起来更加思路清晰和方便
采用注解方式进行配置,配置熔断等方式方便