import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageListener { @RabbitListener(queues = "myQueue") public void handleMessage(String message) { System.out.println("Received message: " + message); // TODO: Process the message } } import org.springframework.amqp.core.AbstractExchange; import org.springframework.amqp.core.AbstractQueue; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Exchange; import org.springframework.amqp.core.Queue; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { @Value("${spring.rabbitmq.host}") private String host; @Value("${spring.rabbitmq.username}") private String username; @Value("${spring.rabbitmq.password}") private String password; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setHost(host); connectionFactory.setUsername(username); connectionFactory.setPassword(password); return connectionFactory; } @Bean public Exchange exchange() { return new DirectExchange("myExchange"); } @Bean public Queue queue() { return new Queue("myQueue"); } @Bean public Binding binding() { return BindingBuilder.bind(queue()).to(exchange()).with("myRoutingKey"); } } import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MessageProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String message) { rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", message); } }


上一篇:
下一篇:
切换中文