Spring Cloud Feign实战来袭:工程中配置断路器Hystrix报错NoClassDefFoundError:HystrixCommandAspect解决方案

这篇具有很好参考价值的文章主要介绍了Spring Cloud Feign实战来袭:工程中配置断路器Hystrix报错NoClassDefFoundError:HystrixCommandAspect解决方案。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、Spring Cloud Feign工程中配置断路器Hystrix

noclassdeffounderror: feign/capability,java,spring cloud,hystrix,java

在Spring Cloud Feign工程中配置断路器Hystrix的时候,pom.xml文件已经加入Hystrix相关的jar:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
		</dependency>

Application.java:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
@EnableHystrixDashboard
public class Application {

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

2、当启动的时候,报如下错误 NoClassDefFoundError:


Exception in thread "main" java.lang.NoClassDefFoundError: com/netflix/hystrix/contrib/javanica/aop/aspectj/HystrixCommandAspect
	at java.lang.Class.getDeclaredMethods0(Native Method)
	at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
	at java.lang.Class.getDeclaredMethods(Class.java:1975)
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
	at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
	at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
	at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
	at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1484)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:515)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:508)
	at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1186)
	at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:818)
	at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:804)
	at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:790)
	at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:744)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)

可以看出来是找不到HystrixCommandAspec.java这个类,于是在github上找到这个源文件:

3、查看源码(切记:一定要学会查看源码)

https://github.com/dmgcodevil/Hystrix/blob/958ec5d7b4bb967be077a4c2bbcdc71e7a7f5248/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop/aspectj/HystrixCommandAspect.java

noclassdeffounderror: feign/capability,java,spring cloud,hystrix,java
源码如下:

/**
 * Copyright 2012 Netflix, Inc.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.netflix.hystrix.contrib.javanica.aop.aspectj;

import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.netflix.hystrix.HystrixExecutable;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.collapser.CommandCollapser;
import com.netflix.hystrix.contrib.javanica.command.CommandExecutor;
import com.netflix.hystrix.contrib.javanica.command.ExecutionType;
import com.netflix.hystrix.contrib.javanica.command.GenericHystrixCommandFactory;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import org.apache.commons.lang3.Validate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;


import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getDeclaredMethod;
import static com.netflix.hystrix.contrib.javanica.utils.AopUtils.getMethodFromTarget;
import static com.netflix.hystrix.contrib.javanica.utils.EnvUtils.isCompileWeaving;
import static com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.getAjcMethodAroundAdvice;

/**
 * AspectJ aspect to process methods which annotated with {@link HystrixCommand} annotation.
 */
@Aspect
public class HystrixCommandAspect {

    private static final Map<HystrixPointcutType, MetaHolderFactory> META_HOLDER_FACTORY_MAP;

    static {
        META_HOLDER_FACTORY_MAP = ImmutableMap.<HystrixPointcutType, MetaHolderFactory>builder()
                .put(HystrixPointcutType.COMMAND, new CommandMetaHolderFactory())
                .put(HystrixPointcutType.COLLAPSER, new CollapserMetaHolderFactory())
                .build();
    }

    @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")

    public void hystrixCommandAnnotationPointcut() {
    }

    @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
    public void hystrixCollapserAnnotationPointcut() {
    }

    @Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")
    public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = getMethodFromTarget(joinPoint);
        Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
        if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {
            throw new IllegalStateException("method cannot be annotated with HystrixCommand and HystrixCollapser " +
                    "annotations at the same time");
        }
        MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get(HystrixPointcutType.of(method));
        MetaHolder metaHolder = metaHolderFactory.create(joinPoint);
        HystrixExecutable executable;
        ExecutionType executionType = metaHolder.isCollapser() ?
                metaHolder.getCollapserExecutionType() : metaHolder.getExecutionType();
        if (metaHolder.isCollapser()) {
            executable = new CommandCollapser(metaHolder);
        } else {
            executable = GenericHystrixCommandFactory.getInstance().create(metaHolder, null);
        }
        Object result;
        try {
            result = CommandExecutor.execute(executable, executionType);
        } catch (HystrixBadRequestException e) {
            throw e.getCause();
        }
        return result;
    }

    /**
     * A factory to create MetaHolder depending on {@link HystrixPointcutType}.
     */
    private static abstract class MetaHolderFactory {
        public MetaHolder create(final ProceedingJoinPoint joinPoint) {
            Method method = getMethodFromTarget(joinPoint);
            Object obj = joinPoint.getTarget();
            Object[] args = joinPoint.getArgs();
            Object proxy = joinPoint.getThis();
            return create(proxy, method, obj, args, joinPoint);
        }

        public abstract MetaHolder create(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint);

        MetaHolder.Builder metaHolderBuilder(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
            MetaHolder.Builder builder = MetaHolder.builder()
                    .args(args).method(method).obj(obj).proxyObj(proxy)
                    .defaultGroupKey(obj.getClass().getSimpleName())
                    .joinPoint(joinPoint);
            if (isCompileWeaving()) {
                builder.ajcMethod(getAjcMethodFromTarget(joinPoint));
            }
            return builder;
        }
    }

    private static class CollapserMetaHolderFactory extends MetaHolderFactory {

        @Override
        public MetaHolder create(Object proxy, Method collapserMethod, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
            HystrixCollapser hystrixCollapser = collapserMethod.getAnnotation(HystrixCollapser.class);
            if (collapserMethod.getParameterTypes().length > 1 || collapserMethod.getParameterTypes().length == 0) {
                throw new IllegalStateException("Collapser method must have one argument: " + collapserMethod);
            }

            Method batchCommandMethod = getDeclaredMethod(obj.getClass(), hystrixCollapser.batchMethod(), List.class);
            if (batchCommandMethod == null || !batchCommandMethod.getReturnType().equals(List.class)) {
                throw new IllegalStateException("required batch method for collapser is absent: "
                        + "(java.util.List) " + obj.getClass().getCanonicalName() + "." +
                        hystrixCollapser.batchMethod() + "(java.util.List)");
            }

            if (!collapserMethod.getParameterTypes()[0]
                    .equals(getGenericParameter(batchCommandMethod.getGenericParameterTypes()[0]))) {
                throw new IllegalStateException("required batch method for collapser is absent, wrong generic type: expected"
                        + obj.getClass().getCanonicalName() + "." +
                        hystrixCollapser.batchMethod() + "(java.util.List<" + collapserMethod.getParameterTypes()[0] + ">), but it's " +
                        getGenericParameter(batchCommandMethod.getGenericParameterTypes()[0]));
            }

            Class<?> collapserMethodReturnType;
            if (Future.class.isAssignableFrom(collapserMethod.getReturnType())) {
                collapserMethodReturnType = getGenericParameter(collapserMethod.getGenericReturnType());
            } else {
                collapserMethodReturnType = collapserMethod.getReturnType();
            }

            if (!collapserMethodReturnType
                    .equals(getGenericParameter(batchCommandMethod.getGenericReturnType()))) {
                throw new IllegalStateException("Return type of batch method must be java.util.List parametrized with corresponding type: expected " +
                        "(java.util.List<" + collapserMethodReturnType + ">)" + obj.getClass().getCanonicalName() + "." +
                        hystrixCollapser.batchMethod() + "(java.util.List<" + collapserMethod.getParameterTypes()[0] + ">), but it's " +
                        getGenericParameter(batchCommandMethod.getGenericReturnType()));
            }

            HystrixCommand hystrixCommand = batchCommandMethod.getAnnotation(HystrixCommand.class);
            if (hystrixCommand == null) {
                throw new IllegalStateException("batch method must be annotated with HystrixCommand annotation");
            }
            // method of batch hystrix command must be passed to metaholder because basically collapser doesn't have any actions
            // that should be invoked upon intercepted method, its required only for underlying batch command
            MetaHolder.Builder builder = MetaHolder.builder()
                    .args(args).method(batchCommandMethod).obj(obj).proxyObj(proxy)
                    .defaultGroupKey(obj.getClass().getSimpleName())
                    .joinPoint(joinPoint);

            if (isCompileWeaving()) {
                builder.ajcMethod(getAjcMethodAroundAdvice(obj.getClass(), batchCommandMethod.getName(), List.class));
            }

            builder.hystrixCollapser(hystrixCollapser);
            builder.defaultCollapserKey(collapserMethod.getName());
            builder.collapserExecutionType(ExecutionType.getExecutionType(collapserMethod.getReturnType()));

            builder.defaultCommandKey(batchCommandMethod.getName());
            builder.hystrixCommand(hystrixCommand);
            builder.executionType(ExecutionType.getExecutionType(batchCommandMethod.getReturnType()));
            return builder.build();
        }
    }

    private static class CommandMetaHolderFactory extends MetaHolderFactory {
        @Override
        public MetaHolder create(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
            HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);
            MetaHolder.Builder builder = metaHolderBuilder(proxy, method, obj, args, joinPoint);
            builder.defaultCommandKey(method.getName());
            builder.hystrixCommand(hystrixCommand);
            builder.executionType(ExecutionType.getExecutionType(method.getReturnType()));
            return builder.build();
        }
    }

    private static enum HystrixPointcutType {
        COMMAND,
        COLLAPSER;

        static HystrixPointcutType of(Method method) {
            return method.isAnnotationPresent(HystrixCommand.class) ? COMMAND : COLLAPSER;
        }
    }

    private static Method getAjcMethodFromTarget(JoinPoint joinPoint) {
        return getAjcMethodAroundAdvice(joinPoint.getTarget().getClass(), (MethodSignature) joinPoint.getSignature());
    }


    private static Class<?> getGenericParameter(Type type) {
        Type tType = ((ParameterizedType) type).getActualTypeArguments()[0];
        String className = tType.toString().split(" ")[1];
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw Throwables.propagate(e);
        }
    }

}

https://github.com/dmgcodevil/Hystrix/tree/958ec5d7b4bb967be077a4c2bbcdc71e7a7f5248/hystrix-contrib/hystrix-javanica
noclassdeffounderror: feign/capability,java,spring cloud,hystrix,java

4、通过查看源码找到解决方案

上面这个图片看到:
noclassdeffounderror: feign/capability,java,spring cloud,hystrix,java

在pom.xml文件中加入:

	<!-- https://mvnrepository.com/artifact/com.netflix.hystrix/hystrix-javanica -->
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
			<version>1.5.12</version>
		</dependency>

问题解决OK!

更多系列文章推荐:文章来源地址https://www.toymoban.com/news/detail-601388.html

  1. Spring Cloud (20) | Spring Cloud Bus 使用kafka消息总线、gitlab添加webhooks实现自动刷新配置
  2. Spring Cloud (19) | Eureka Server 高可用服务注册中心
  3. Spring Cloud (18) | 给Eureka Server加上安全验证
  4. Spring Cloud (15) | Spring Boot、HikariCP、Mybatis和MySQL 配置HikariCP数据库连接池
  5. Spring Cloud (14) | 微服务不能从git/github/gitlab中获取数据库信息 can’t load properties from git/github/gitlab
  6. Spring Cloud (12) | Spring Cloud Zuul网关调用微服务,request请求参数是application/json
  7. Spring Cloud (11) | healthcheck开启健康检查
  8. Spring Cloud (10) | Eureka 各项参数详解
  9. Spring Cloud (8) | 把Spring Boot项目改造成tomcat容器启动
  10. Spring Cloud (7) | Mongodb 微服务
  11. Spring Cloud (6) | spring cloud zuul 跨域问题No ‘Access-Control-Allow-Origin’ header
  12. Spring Cloud (5) | 配置中心 Config Server 配置git or github or gitlab
  13. Spring Cloud (3) | spring cloud bus 消息总线kafka应用
  14. Spring Cloud (1) | java.net.UnknownHostException: eureka-server

到了这里,关于Spring Cloud Feign实战来袭:工程中配置断路器Hystrix报错NoClassDefFoundError:HystrixCommandAspect解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Spring Cloud系列】Feign详解与实战

    在前一章介绍了Ribbon的用法,在使用Ribbon是通过RestTemplate调用其他服务的API时,所有参数必须在请求的URL中进行拼接。如果参数过多,拼接请求字符串会导致效率下降。Spring Cloud提供另外一种调用API的解决方案,既使用 Spring Cloud Feign 。 Feign是一种负载均衡的HTTP客户端,它封

    2024年02月07日
    浏览(34)
  • Spring Cloud 实战 | 解密Feign底层原理,包含实战源码

    专栏集锦,大佬们可以收藏以备不时之需 Spring Cloud实战专栏:https://blog.csdn.net/superdangbo/category_9270827.html Python 实战专栏:https://blog.csdn.net/superdangbo/category_9271194.html Logback 详解专栏:https://blog.csdn.net/superdangbo/category_9271502.html tensorflow专栏:https://blog.csdn.net/superdangbo/category_869

    2024年02月06日
    浏览(40)
  • SpringCloud之断路器聚合监控

    看单个的Hystrix Dashboard的数据并没有什么多大的价值,要想看这个系统的Hystrix Dashboard数据就需要用到Hystrix Turbine。Hystrix Turbine将每个服务Hystrix Dashboard数据进行了整合。Hystrix Turbine的使用非常简单,只需要引入相应的依赖和加上注解和配置就可以了。 本文使用的工程为上一篇

    2024年02月13日
    浏览(31)
  • es 报错 Data too large 触发断路器

    报错原因是 es 在 full GC 之前触发了默认的断路器,导致报错 [parent] Data too large ,相似的报错内容如下: 查看当前 es 节点的 jvm 内存使用情况(ip和端口要换成自己的 es 节点) heap.current 当前使用的内存 heap.percent 内存使用量百分比 heap.max 内存最大值 如果本机内存足够,并且

    2024年01月18日
    浏览(59)
  • SpringCloud搭建微服务之Circuit Breaker断路器

    Circuit breaker是一套规范和接口,落地实现是Resilience4j,Resilience4j是一个专为函数式编程设计的轻量级容错库,Resilience4j提供高阶函数(装饰器),以通过断路器、速率限制器、重试或隔板增强任何功能接口、lambda表达式或方法引用。可以在任何函数式接口、lambda表达式或方法

    2024年04月27日
    浏览(26)
  • 【云原生】Spring Cloud Alibaba 之 Feign 远程调用 实战

    在分布式领域中,一个系统由很多服务组成,不同的服务由各自的进程单独负责。因此,远程调用在分布式通信中尤为重要。 远程调用可分如下两类: 本地过程调用(Local Procedure Call,LPC) ,是指同一台机器上运行的不同进程之间的互相通信,即在多进程操作系统中,运行

    2023年04月09日
    浏览(44)
  • 微服务治理:微服务断路器(微服务故障隔离模式)详解

    微服务断路器是一种设计模式,可以保护系统免于级联故障,通过限制对故障服务的调用来实现。它的工作原理类似于电气断路器:当服务遇到问题时,它会切断请求流,使其有机会恢复,并防止其他服务被压垮。 工作原理: 闭合状态(正常运行): 断路器初始处于此状态

    2024年01月17日
    浏览(45)
  • 【Spring Cloud】基于 Feign 实现远程调用,深入探索 Feign 的自定义配置、性能优化以及最佳实践方案

    在微服务架构中,服务之间的通信是至关重要的,而远程调用则成为实现这种通信的一种常见方式。在 Java 中,使用 RestTemplate 是一种传统的远程调用方式,但它存在一些问题,如代码可读性差、编程体验不一致以及参数复杂URL难以维护等。 在本文中,我们将探讨如何通过使

    2024年02月04日
    浏览(50)
  • Spring Cloud - HTTP 客户端 Feign 、自定义配置、优化、最佳实践

    目录 一、OpenFeign 是什么,有什么用呢? 二、OpenFeign 客户端的使用 2.1、远程调用 1.引入依赖 2.在order-service(发起远程调用的微服务)的启动类添加注解开启Feign的功能 3.编写 OpenFeign 客户端 4.通过 OpenFeign 客户端发起远程调用 2.2、自定义 OpenFeign 配置 1.配置文件方式 2.j

    2024年02月16日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包