Java Spring send back message to queue from consumer

yenk :

I have a service that sends message to rabbitmq and the consumer do some manipulation of the message and re-queue them.

I can successfully send to rabbitmq the initial message but the problem is i cannot resend to rabbitmq any consumed message if the message requires modifications.

@Service
public class MyService {

    /**
     * The template
     */
    @Autowired
    private AmqpTemplate amqpTemplate;
    private final RabbitMQConfig config;

    public void send(String message) {
        try {
            amqpTemplate.convertAndSend("ex", "r", message);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Then in my config i have setup: @Bean public ConnectionFactory connectionFactory() { /* working code */ }

@Bean
public Queue myQueue() { return new Queue("my-queue"); 
// etc...

@Bean
MessageListenerAdapter myListenerAdapter(MyListener listener) {
    return new MessageListenerAdapter(listener, "listener");
}

@Bean
MyListener myListener() {
    return new MyListener();
}

then...

public class MyListener {
    public void receiveMessage(String message) { 
        // ... some code
        // if message requires modification, then repush
        new Repush().push(message);
    }
}

I tried to create a new class with new but the "myService" always null

@Component
public class Repush {
    @Autowired
    private MyService myService;

    public void push(String message) {
        // myService is null at this point
    }
}
Демьян Бельский :

Don't use new for bean creation. Spring injects fields only in beans. Your MyListener is a bean. Just add Repush field with @Autowired annotation in this class.

public class MyListener {
    @Autowired
    private Repush repush;

    public void receiveMessage(String message) { 
        // ... some code
        // if message requires modification, then repush
        repush.push(message);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102487&siteId=1