本文主要是介绍openfeign+Sentinel 实现熔断,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
openfeign 是为 HTTP 形式的 Rest API 提供了非常简洁高效的 RPC 调用方式,自行集成rabbion 实现负载,熔断需要借助Hystrix、Sentinel。
为何选择Sentinel而不用Hystrix?
pom文件如下
<properties><spring-boot.version>2.3.11.RELEASE</spring-boot.version><spring-cloud.version>Hoxton.SR9</spring-cloud.version> <maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency> <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-loadbalancer</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></dependency> <dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId><version>2.2.5.RELEASE</version></dependency></dependencies> <dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies> </dependencyManagement>
bootstrap.yml 配置如下
server: port: 8890 feign: sentinel: enabled: true client: config: default: loggerLevel: FULL connectTimeout: 5000 readTimeout: 10000
启动类上需加上@EnableFeignClients注解 开启feign
@SpringBootApplication @EnableFeignClients public class NacosConsumerApplication { public static void main(String[] args) {SpringApplication.run(NacosConsumerApplication.class, args);} }
@FeignClient修饰接口
注意@FeignClient(name = "随便取名称,必须要有",url = "调用对方接口的url",fallback = 熔断回调)
@FeignClient(name = "pay",url = "http://127.0.0.1:8880",fallback = TestServiceImpl.class) public interface TestService {@GetMapping("/server/getServer")String getPayMent(@RequestParam("s") String s); }
fallback回调类
@Service public class TestServiceImpl implements TestService {@Overridepublic String getPayMent(String s) {return "报错了!!!!!!";} }
方法调用
@Controller @RequestMapping("consumer") public class ConfigController { @Autowiredprivate TestService testService; @RequestMapping(value = "/getServer", method = GET)@ResponseBodypublic String get(String s) {return testService.getPayMent(s);} @RequestMapping(value = "/getConsumer", method = GET)@ResponseBodypublic String getTest() {return "hello, i am Consumer";} }
由于 server端没有启动,故此时调用http://localhost:8890/consumer/getServer该方法会进入到熔断回调方法中。
开始启动server 重新调用http://localhost:8890/consumer/getServer 此时能够看到正常访问
openfeiign工作原理
1、通过启动类上@EnableFeignClients,触发扫描@FeignClient修饰类
2、解析到 @FeignClient 修饰类后, Feign 框架通过扩展 Spring Bean Deifinition 的注册逻辑, 最终注册一个 FeignClientFacotoryBean 进入 Spring 容器
// FeignClientsRegistrar 类中此方法 public void registerFeignClients(AnnotationMetadata metadata,BeanDefinitionRegistry registry) { LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName());AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(FeignClient.class);final Class<?>[] clients = attrs == null ? null: (Class<?>[]) attrs.get("clients");if (clients == null || clients.length == 0) {// 扫描有@FeignClient注解的类ClassPathScanningCandidateComponentProvider scanner = getScanner();scanner.setResourceLoader(this.resourceLoader);scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));Set<String> basePackages = getBasePackages(metadata);for (String basePackage : basePackages) {candidateComponents.addAll(scanner.findCandidateComponents(basePackage));}}else {for (Class<?> clazz : clients) {candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz));}} for (BeanDefinition candidateComponent : candidateComponents) {if (candidateComponent instanceof AnnotatedBeanDefinition) {// 校验@FeignClient注解只能加在接口类上// verify annotated class is an interfaceAnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();Assert.isTrue(annotationMetadata.isInterface(),"@FeignClient can only be specified on an interface"); Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(FeignClient.class.getCanonicalName()); String name = getClientName(attributes);registerClientConfiguration(registry, name,attributes.get("configuration"));//最终通过调用 Spring 框架中的 BeanDefinitionReaderUtils.resgisterBeanDefinition 将解析处理过的 FeignClient BeanDeifinition 添加到 spring 容器中registerFeignClient(registry, annotationMetadata, attributes);}} }
private void registerFeignClient(BeanDefinitionRegistry registry,AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {String className = annotationMetadata.getClassName();BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);。。。省略 }
3、通过FeignClientFacotoryBean类中
@Override public Object getObject() throws Exception {return getTarget(); }/*** @param <T> the target type of the Feign client* @return a {@link Feign} client created with the specified data and the context* information*/ <T> T getTarget() {FeignContext context = applicationContext.getBean(FeignContext.class);Feign.Builder builder = feign(context);if (!StringUtils.hasText(url)) {if (!name.startsWith("http")) {url = "http://" + name;}else {url = name;}url += cleanPath();return (T) loadBalance(builder, context,new HardCodedTarget<>(type, name, url));}// 省略。。。。。// 通过查看Feign.target()return (T) targeter.target(this, builder, context,new HardCodedTarget<>(type, name, url)); }
// 通过Feign类中的target方法得知,InvocationHandler处理好后,通过代理转行成对应的对象
public <T> T target(Target<T> target) {return build().newInstance(target);}
@Overridepublic <T> T newInstance(Target<T> target) {Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);// 。。。。代码省略InvocationHandler handler = factory.create(target, methodToHandler);T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(),new Class<?>[] {target.type()}, handler);for (DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {defaultMethodHandler.bindTo(proxy);}return proxy;}
这篇关于openfeign+Sentinel 实现熔断的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!