在Spring Integration中为Redis创建MessageSource

时间:2018-11-21 07:30:04

标签: java redis spring-integration

我想配置InboundChannelAdapter,以便它应该从redis队列中弹出消息,并将其传递给基于Java的注释中的ServiceActivator(仅,避免使用XML)。我从Spring文档中找到了代码:

@Bean("someAdapter.source")
@EndpointId("someAdapter")
@InboundChannelAdapter(channel = "channel3", poller = @Poller(fixedDelay = "5000"))
public MessageSource<?> source() {
    return () -> {
        ...
    };
}

但是我不明白的是,如何通过使用redisConnectionFactory从redis队列中弹出数据来返回MessageSource?

换句话说,如何在基于Java的注释中做到这一点?

  <int-redis:queue-inbound-channel-adapter id="postPublicationInboundAdapter"
                                             connection-factory="redisConnectionFactory"
                                             channel="postPublicationChannel"
                                             error-channel="postPublicationLoggingChannel"
                                             receive-timeout="5000"
                                             queue="archive.post.publication.queue"
                                             serializer="postPublicationJsonRedisSerializer"/>

1 个答案:

答案 0 :(得分:1)

让我们从这里开始:https://docs.spring.io/spring-integration/docs/5.0.9.RELEASE/reference/html/overview.html#programming-tips

  

借助XML配置和Spring Integration命名空间支持,XML解析器隐藏了如何声明目标bean并将它们连接在一起。对于Java和注释配置,重要的是要了解面向目标最终用户应用程序的Framework API。

然后,我们为此<int-redis:queue-inbound-channel-adapter>打开一个XSD:

 <xsd:element name="queue-inbound-channel-adapter">
    <xsd:annotation>
        <xsd:documentation>
            Defines a Message Producing Endpoint for the
            'org.springframework.integration.redis.inbound.RedisQueueMessageDrivenEndpoint' for listening a Redis
            queue.
        </xsd:documentation>
    </xsd:annotation>

因此,听起来int-redis:queue-inbound-channel-adapter不是MessageSource。因此@InboundChannelAdapter是死胡同。我同意XML元素的名称是错误的,但是现在将其重命名已经为时已晚。

从这里我们也发现我们需要处理RedisQueueMessageDrivenEndpoint。而且由于它是消息驱动的自我管理,因此我们不需要任何特殊的注释。足以将它声明为这样的bean:

@Bean
RedisQueueMessageDrivenEndpoint redisQueueMessageDrivenEndpoint(RedisConnectionFactory redisConnectionFactory, RedisSerializer<?> serializer) {
    RedisQueueMessageDrivenEndpoint endpoint =
                new RedisQueueMessageDrivenEndpoint("archive.post.publication.queue", redisConnectionFactory);
    endpoint.setOutputChannelName("postPublicationChannel");
    endpoint.setErrorChannelName("postPublicationLoggingChannel");
    endpoint.setReceiveTimeout(5000);
    endpoint.setSerializer(serializer);
    return endpoint;
}