简介
Openfeign 实现远程接口映射,与Sentinel整合同Hystrix 整合非常类似,只需要在配置文件中启用feign.sentinel.enabled=true 即可开启Openfeign与Sentinel熔断处理。
实现
1.service-consumer 模块添加openfeign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.service-consumer 模块配置 feign.sentinel.enabled=true
3.启动类使用@EnableFeignClients启用 Feign支持
4.建立远程接口映射ITestFeign.java
package com.vincent.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
@FeignClient(value = "nacos-provider",fallback = TestFeignFallback.class)
public interface ITestFeign {
@GetMapping("/test")
Map<String,Object> test();
}
5.建立ITestFeign 实现类作为失败回退处理
package com.vincent.feign;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class TestFeignFallback implements ITestFeign{
@Override
public Map<String, Object> test() {
Map<String,Object> rst = new HashMap<>();
rst.put("msg","请求熔断处理");
return rst;
}
}
6.启动服务消费者并访问 http://localhost:8020/consumer/test
7.配置Sentinel流控
频繁访问 http://localhost:8020/consumer/test
官方资料:https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html