You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache Camel结合spring-event组件实现Spring3.x事件生产消费示例求助

基于Apache Camel spring-event组件的改造实现

前置依赖配置

首先在项目依赖中引入对应Spring版本适配的camel-spring-event组件,Maven配置示例如下:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-spring-event</artifactId>
    <version>适配当前Spring版本的稳定版</version>
</dependency>

如果使用Spring Boot,可额外引入对应版本的camel-spring-boot-starter实现自动配置。


1. 自定义事件类(无需修改)

原有自定义事件类可以直接复用,代码如下:

public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

2. 事件消费路由(替代原生事件监听器)

新增Camel路由实现事件监听消费,替换原有@EventListener注解的监听器实现:

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class CustomSpringEventRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        // 配置消费端点,指定监听的自定义事件全类名,避免接收其他Spring系统事件
        from("spring-event:customEventConsumer?eventClass=替换为你的自定义事件全类名.CustomSpringEvent")
                .process(exchange -> {
                    CustomSpringEvent event = exchange.getIn().getBody(CustomSpringEvent.class);
                    System.out.println("Camel路由接收到Spring自定义事件 - " + event.getMessage());
                    // 此处可扩展其他消费逻辑
                });
    }
}

3. 事件发布实现(替代原生事件发布器)

两种实现方式可按需选择:

方式一:直接使用Camel ProducerTemplate发布

在需要发布事件的业务类中注入ProducerTemplate直接发布:

// 注入生产者模板
@Autowired
private ProducerTemplate producerTemplate;

// 发布事件逻辑
public void publishCustomEvent(String message) {
    System.out.println("通过Camel发布自定义事件");
    CustomSpringEvent event = new CustomSpringEvent(this, message);
    producerTemplate.sendBody("spring-event:applicationEventPublisher", event);
}

方式二:保留原有发布器接口兼容旧代码

如果不想修改原有调用CustomSpringEventPublisher的业务代码,可直接改造原有发布器实现:

@Component
public class CustomSpringEventPublisher {
    @Autowired
    private ProducerTemplate producerTemplate;

    public void publishCustomEvent(final String message) {
        System.out.println("Publishing custom event. ");
        CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
        producerTemplate.sendBody("spring-event:applicationEventPublisher", customSpringEvent);
    }
}

功能验证

启动Spring容器后调用事件发布逻辑,即可看到Camel路由的消费逻辑正常输出事件内容,效果与原生Spring事件实现完全一致。

内容的提问来源于stack exchange,提问作者d-man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:09:02