【问题标题】:Spring Microservices issue with @HystrixCommand@HystrixCommand 的 Spring 微服务问题
【发布时间】:2017-04-27 22:33:15
【问题描述】:

我们在 Spring Boot / Cloud 微服务中遇到了 Hystrix 命令的问题。我们有一个 Spring 组件,其中包含一个用 @RabbitListener 注释的方法。当新消息到达时,该方法将调用委托给NotificationService::processNotification()

NotificationService 是一个带有 @Service 注释的 bean。方法processNotification() 可以请求第三方应用程序。我们希望使用@HystrixCommand 包装第三方应用程序的调用以提供容错,但由于某些原因,Hystrix Command 注释方法不起作用。

如果我们调用一个 Controller 并且 Controller 将调用委托给一个 Service 方法,该方法又具有一个 Hystrix Command ,那么一切都会完美运行。当微服务消费一条消息时,Hystrix Command 的唯一问题就出现了,而且似乎 Hystrix Command 没有触发回退方法。

这是无效的代码:

@Component
public class MessageProcessor {

    @Autowired
    private NotificationService notificationService;

    @RabbitListener(queues = "abc.xyz-queue")
    public void onNewNotification(String payload) {
        this.notificationService.processNotification(payload);
    }

}

@Service
public class NotificationService {

    public void processNotification(String payload) {
        ...
        this.notifyThirdPartyApp(notificationDTO);
        ...
    }

    @HystrixCommand(fallbackMethod = "notifyThirdPartyAppFallback")
    public void notifyThirdPartyApp(NotificationDTO notificationDTO) {
        //Do stuff here that could fail
    }

    public void notifyThirdPartyAppFallback(NotificationDTO notificationDTO) {
        // Fallbacl impl goes here
    }

}

@SpringBootApplication
@EnableCaching
@EnableCircuitBreaker
@EnableDiscoveryClient
@EnableRabbit
public class NotificationApplication {

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

【问题讨论】:

  • 贴一些代码而不是描述它。

标签: spring spring-boot spring-amqp hystrix


【解决方案1】:

不看代码我不确定你的问题。

您可以采取另一种方法:不要在服务中使用注释来描述此调用,只需扩展 HystrixCommand 并在其中实现 api 调用逻辑 (read more):

public class CommandHelloWorld extends HystrixCommand<String> {

    private final String name;

    public CommandHelloWorld(String name) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.name = name;
    }

    @Override
    protected String run() {
        // a real example would do work like a network call here
        return "Hello " + name + "!";
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-04-28
    • 2018-03-18
    • 2023-02-03
    • 2022-01-24
    • 2021-06-05
    • 2019-05-26
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多