【问题标题】:How to create channel interceptor programmatically in spring如何在春季以编程方式创建通道拦截器
【发布时间】:2014-07-21 03:17:07
【问题描述】:

我想以编程方式按需创建以下 XML 配置:

<int-mqtt:message-driven-channel-adapter id="inboundAdapter"
        client-id="${mqtt.client.id}"
        url="${mqtt.broker.url}"
        topics="${mqtt.subscribed.topics}"
        client-factory="clientFactory"
        channel="input-channel-1" converter="customConverter" />

    <int:channel id="input-channel-1">
        <int:queue/>
        <int:interceptors>
            <int:wire-tap channel="logger"/>
            <int:ref bean="messageListener"/>
        </int:interceptors>
    </int:channel>

    <int:channel id="logger" />

    <int:logging-channel-adapter channel="logger"
    auto-startup="true" level="INFO" id="loggerAdapter" log-full-message="true" />

我能做的如下

CustomMqttPahoMessageDrivenChannelAdapter adapter = new CustomMqttPahoMessageDrivenChannelAdapter(url, clientId, topic);
adapter.setOutputChannel(outputChannel);
adapter.setConverter(ctx.getBean("customConverter", MyPahoMessageConverter.class));

现在我需要添加拦截器 bean,通过它每个客户端将在消息到达时分别根据他们订阅的主题得到通知。

我想要实现的是:

1) 客户端连接服务器时创建mqtt适配器。(每个客户端将根据配置订阅不同的主题)

2) 客户端断开连接时释放 mqtt 适配器。

谁能帮我解决这个问题?

【问题讨论】:

    标签: spring spring-integration mqtt


    【解决方案1】:

    不清楚你想做什么;您在 XML 配置中的 input-channel-1 下游有什么。

    messageListener 是做什么的?

    将业务逻辑放在通道中是一种反模式;除非它是真正轻量级的东西,否则请考虑使用 &lt;service-activator/&gt; 来调用它 - 可能通过将 input-channel-1 设为 pub-sub 频道。

    要回答您的简单问题,添加拦截器,您可以使用outputChannel.addInterceptor(ctx.getBean("messageListener", ChannelInterceptor.class));

    【讨论】:

    • messageListener 是一个扩展 ChannelInterceptorAdapter 并覆盖其 preSend(message,channel) 方法的 bean 类。拦截器方法内部的逻辑是重量级的,所以我不应该更喜欢这种添加通道拦截器的方法。我将从spring-doc 看一下。不错的收获!顺便说一句,我可以即时创建服务激活器吗?
    • 我没有输入通道 1 的任何下游配置。当消息不断到达时,队列将达到其容量(?)并导致异常情况?
    • 你想传达这个((AbstractMessageChannel)outputChannel).addInterceptor(ctx.getBean("messageListener", ChannelInterceptor.class)); 吗?
    • 是的,你会耗尽内存;你绝对不应该以这种方式使用拦截器。是的,您可以即时创建“服务激活器”——只需实现MessageHandler,将频道设为DirectChannel 并订阅您的处理程序即可。我建议您阅读the Spring Integration documentation 并查看some of the samples
    • 非常感谢!! MessageHandler 拯救了我的一天.. :)
    猜你喜欢
    • 2020-01-02
    • 2017-06-11
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多