最新の安定バージョンについては、spring-cloud-stream 5.1.0 を使用してください。

カスタムバインダーの実装

カスタム Binder を実装するには、次のことを行うだけです。

  • 必要な依存関係を追加します

  • ProvisioningProvider 実装を提供する

  • MessageProducer 実装を提供する

  • MessageHandler 実装を提供する

  • バインダーの実装を提供する

  • バインダー構成を作成する

  • META-INF/spring.binders でバインダーを定義します

必要な依存関係を追加します

spring-cloud-stream 依存関係をプロジェクトに追加します(例: Maven の場合):

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream</artifactId>
    <version>${spring.cloud.stream.version}</version>
</dependency>

ProvisioningProvider 実装を提供する

ProvisioningProvider は、コンシューマーとプロデューサーの宛先のプロビジョニングを担当し、物理的な宛先参照の application.yml または application.properties ファイルに含まれる論理的な宛先を変換する必要があります。

入出力バインディング構成を介して提供される宛先を単純にトリミングする ProvisioningProvider 実装の例を以下に示します。

public class FileMessageBinderProvisioner implements ProvisioningProvider<ConsumerProperties, ProducerProperties> {

    @Override
    public ProducerDestination provisionProducerDestination(
            final String name,
            final ProducerProperties properties) {

        return new FileMessageDestination(name);
    }

    @Override
    public ConsumerDestination provisionConsumerDestination(
            final String name,
            final String group,
            final ConsumerProperties properties) {

        return new FileMessageDestination(name);
    }

    private class FileMessageDestination implements ProducerDestination, ConsumerDestination {

        private final String destination;

        private FileMessageDestination(final String destination) {
            this.destination = destination;
        }

        @Override
        public String getName() {
            return destination.trim();
        }

        @Override
        public String getNameForPartition(int partition) {
            throw new UnsupportedOperationException("Partitioning is not implemented for file messaging.");
        }

    }

}

MessageProducer 実装を提供する

MessageProducer は、イベントを消費し、そのようなイベントを消費するように構成されたクライアントアプリケーションへのメッセージとして処理する責任があります。

これは、MessageProducerSupport 抽象化を継承して、トリミングされた宛先名に一致し、プロジェクトパスにあるファイルをポーリングすると同時に、読み取りメッセージをアーカイブし、結果として生じる同一のメッセージを破棄する MessageProducer 実装の例です。

public class FileMessageProducer extends MessageProducerSupport {

    public static final String ARCHIVE = "archive.txt";
    private final ConsumerDestination destination;
    private String previousPayload;

    public FileMessageProducer(ConsumerDestination destination) {
        this.destination = destination;
    }

    @Override
    public void doStart() {
        receive();
    }

    private void receive() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

        executorService.scheduleWithFixedDelay(() -> {
            String payload = getPayload();

            if(payload != null) {
                Message<String> receivedMessage = MessageBuilder.withPayload(payload).build();
                archiveMessage(payload);
                sendMessage(receivedMessage);
            }

        }, 0, 50, MILLISECONDS);
    }

    private String getPayload() {
        try {
            List<String> allLines = Files.readAllLines(Paths.get(destination.getName()));
            String currentPayload = allLines.get(allLines.size() - 1);

            if(!currentPayload.equals(previousPayload)) {
                previousPayload = currentPayload;
                return currentPayload;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    private void archiveMessage(String payload) {
        try {
            Files.write(Paths.get(ARCHIVE), (payload + "\n").getBytes(), CREATE, APPEND);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
カスタムバインダーを実装する場合、既存の MessageProducer 実装を常に使用できるため、この手順は厳密には必須ではありません。

MessageHandler 実装を提供する

MessageHandler は、イベントを生成するために必要なロジックを提供します。

MessageHandler の実装例を次に示します。

public class FileMessageHandler implements MessageHandler{

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        //write message to file
    }

}
カスタムバインダーを実装する場合、既存の MessageHandler 実装を常に使用できるため、この手順は厳密には必須ではありません。

バインダーの実装を提供する

これで、Binder 抽象化の独自の実装を提供できるようになりました。これは、次の方法で簡単に実行できます。

  • AbstractMessageChannelBinder クラスの拡張

  • ProvisioningProvider を AbstractMessageChannelBinder のジェネリクス引数として指定する

  • createProducerMessageHandler および createConsumerEndpoint メソッドのオーバーライド

例:

public class FileMessageBinder extends AbstractMessageChannelBinder<ConsumerProperties, ProducerProperties, FileMessageBinderProvisioner> {

    public FileMessageBinder(
            String[] headersToEmbed,
            FileMessageBinderProvisioner provisioningProvider) {

        super(headersToEmbed, provisioningProvider);
    }

    @Override
    protected MessageHandler createProducerMessageHandler(
            final ProducerDestination destination,
            final ProducerProperties producerProperties,
            final MessageChannel errorChannel) throws Exception {

        return message -> {
            String fileName = destination.getName();
            String payload = new String((byte[])message.getPayload()) + "\n";

            try {
                Files.write(Paths.get(fileName), payload.getBytes(), CREATE, APPEND);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
    }

    @Override
    protected MessageProducer createConsumerEndpoint(
            final ConsumerDestination destination,
            final String group,
            final ConsumerProperties properties) throws Exception {

        return new FileMessageProducer(destination);
    }

}

バインダー構成を作成する

バインダー実装(および必要になる可能性のある他のすべての Bean)の Bean を初期化するために、Spring 構成を作成することが厳密に必要です。

@Configuration
public class FileMessageBinderConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public FileMessageBinderProvisioner fileMessageBinderProvisioner() {
        return new FileMessageBinderProvisioner();
    }

    @Bean
    @ConditionalOnMissingBean
    public FileMessageBinder fileMessageBinder(FileMessageBinderProvisioner fileMessageBinderProvisioner) {
        return new FileMessageBinder(null, fileMessageBinderProvisioner);
    }

}

META-INF/spring.binders でバインダーを定義します

最後に、クラスパスの META-INF/spring.binders ファイルでバインダーを定義し、バインダーの名前とバインダー構成クラスの完全修飾名の両方を指定する必要があります。

myFileBinder:\
com.example.springcloudstreamcustombinder.config.FileMessageBinderConfiguration