Spring Cloud Alibaba学习笔记(13) - Spring Cloud Stream的监控与异常处理

Spring Cloud Stream监控

Spring Boot Actuator组件用于暴露监控端点,很多监控工具都需要依赖该组件的监控端点实现监控。而项目集成了Stream及Actuator后也会暴露相应的监控端点.

首先需要在项目里集成Actuator,添加依赖如下:

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

添加配置,暴露所有监控端点,并显示健康检测详情

management:
  endpoint:
    health:
      # 显示健康检测详情
      show-details: always
  endpoints:
    web:
      exposure:
        # 暴露所有监控端点
        include: '*'

访问http://localhost:端口号/actuator可以获取所有暴露出来的监控端点,Stream的相关监控端点也在其中

/actuator/bindings端点可以用于查看bindings相关信息:

/actuator/channels端点用于查看channels的相关信息,“input”和“output”就是channel,可以认为这些channel是topic的抽象:

/actuator/health端点中可以查看binder及RocketMQ的状态,主要是用于查看MQ的连接情况,如果连接不上其status则为DOWN:

Spring Cloud Stream异常处理

局部处理

配置文件

spring:
  cloud:
    stream:
      bindings:
        input:
          destination: test-destination
          group: test-group
        output:
          destination: test-destination

代码实现

@Slf4j
@SpringBootApplication
@EnableBinding({Processor.class})
@EnableScheduling
public class Study01Application {
    public static void main(String[] args) {
        SpringApplication.run(Study01Application.class, args);
    }

    @StreamListener(value = Processor.INPUT)
    public void handle(String body) {
        throw new RuntimeException("运行时错误");
    }

    @ServiceActivator(inputChannel = "test-destination.test-group.errors")
    public void handleError(ErrorMessage message) {
        Throwable throwable = message.getPayload();
        log.error("截获异常", throwable);

        Message<?> originalMessage = message.getOriginalMessage();
        assert originalMessage != null;

        log.info("原始消息体 = {}", new String((byte[]) originalMessage.getPayload()));
    }

    @Bean
    @InboundChannelAdapter(value = Processor.OUTPUT, poller = @Poller(fixedDelay = "1000", maxMessagesPerPoll = "1"))
    public MessageSource<String> test() {
        return () -> new GenericMessage<>("qwer");
    }
}

全局处理

代码实现

@StreamListener(value = Processor.INPUT)
public void handle(String body) {
    throw new RuntimeException("运行时错误");
}

@StreamListener("errorChannel")
public void error(Message<?> message) {
    ErrorMessage errorMessage = (ErrorMessage) message;
    log.warn("Handling ERROR = {} " + errorMessage);
}
posted @ 2019-10-26 12:29  夜的那种黑丶  阅读(1400)  评论(0编辑  收藏  举报