Home > Back-end >  Spring cloud stream functional producer/consumer bean is not working when declared out side of @Spri
Spring cloud stream functional producer/consumer bean is not working when declared out side of @Spri

Time:12-10

if userProducer is placed in a separate class, it is not getting triggered, for example via StreamBridge.

package com.moments.auth;

import com.moments.auth.payload.UserEventPayload;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.context.annotation.Bean;

import java.util.function.Function;
import java.util.function.Supplier;

@SpringBootApplication
public class AuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthApplication.class, args);
    }


    @Bean
    public Function<UserEventPayload, UserEventPayload> userProducer(){
        return userEventPayload -> {
            return userEventPayload;
        };
    }

}

YAML file

  cloud:
    stream:
      function:
        definition: userProducer
      bindings:
        userProducer-out-0:
          destination: user
      kafka.binder:
        brokers: 127.0.0.1
        defaultBrokerPort: 9092

Placing in separate class


package com.moments.auth.messaging;


import com.moments.auth.payload.UserEventPayload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.Function

@Component
@Slf4j
public class UserEventSender {

    @Bean
    public Function<UserEventPayload, UserEventPayload> userProducer(){
        return userEventPayload -> {
            return userEventPayload;
        };
    }

}

what should I need to do if userProducer binding needs to work if its place out of the main class?

Update-1 added the package names

CodePudding user response:

You defined a Function bean, which means that your application is now a processor (Supplier for Source and Consumer for Sink).

A Processor will receive messages from a input binding topic, process them and put it down to a output binding topic (userProducer-out-0.destination=user in your case)


You need to define a input binding, for example:

bindings:
    userProducer-in-0:
      destination: inputTopic
      group: groupTest
    userProducer-out-0:
      destination: user

Your UserEventSender class belongs to com.moments.auth.messaging package which is a sub package of your main class com.moments.auth. It's ok now and will be scanned by @ComponentScan in @SpringBootApplication.

CodePudding user response:

You UserEventSender is annotated with @Component instead of @Configuration.

While @Configuration is also a @Component (for component scanning purposes), @Component is not @Configuration as it implies a single component.

  • Related