RabbitMQ使用例子

一些概念:

 Topic:

        在不同的消息中间件中, Topic可能对应着不同的概念,

        比如:在RabbitMQ中的它对应了Exchange、而在Kakfa中则对应了Kafka中的Topic。

    消息组:

        默认情况下,当没有为应用指定消费组的时候,Spring Cloud Stream会为其分配一个独立的匿名消费组。

        当一个消费组中有多个应用实例,只会有一个成员真正的收到消息并进行处理。

    消息分区:

        当生产者将消息数据发送给多个消费者实例时,保证拥有共同特征的消息数据始终是由同一个消费者实例接收和处理

        

1.创建SpringBoot 项目:Eureka 和 Rabbitmq_hello 两个项目

其中对于Rabbitmq_hello 项目加入RabbitMQ依赖:

                <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

2. 编写配置类RabbitConfig ,   用来配置队列、交换器、路由等高级信息

/**
 * 创建RabbitMQ的配置类 RabbitConfig,用来配置队列、交换器、路由等高级信息。
 */
@Configuration
public class RabbitConfig {

    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
}

3. 创建消息发送类:Sender

/**
 *
 * 通过注入 AmqpTemplate接口的实例来实现消息的发送,
 * AmqpTemplate接口定义了一套针对AMQP协议的基础操作。
 *
 * 在该生产者,我们会产生一个字符串,并发送到名为 hello的队列中。
 */
@Component
public class Sender {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send() {
        String context = "hello " + new Date();
        System.out.println("sender: " + context);
        this.amqpTemplate.convertAndSend("hello",context);
    }
}

4. 创建消息接收类:Receiver

@Component
@RabbitListener(queues = "hello")
public class Receiver {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver:" + hello);
    }
}

5. 写个测试类: 

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ServerRabbitmqHelloApplicationTests {

	@Autowired
	private Sender sender;

	@Test
	public void hello() throws Exception {
		sender.send();
	}
}

6. 测试结果截图:



7. 总结:

对于 @RabbitListener 这个注解要注意

1.在启动类上添加@EnableRabbit注解

2.在Spring容器中托管一个RabbitListenerContainerFactory,默认实现类SimpleRabbitListenerContainerFactory

3.编写一个消息处理器类托管到Spring容器中,并使用@RabbitListener注解标注该类为RabbitMQ的消息处理类

4.使用@RabbitHandler注解标注在方法上,表示当有收到消息的时候,就交给带有@RabbitHandler的方法处理,

具体找哪个方法需要根据MessageConverter转换后的对象类型决定


8.参考:纯洁的微笑博客


9. rabbitmq菜单管理 :http://localhost:15672/


查看创建的hello队列



修改Receiver 类:

@Component
public class Receiver {

    @RabbitHandler
    @RabbitListener(queues = "hello")
    public void process(byte[] hello) {
        System.out.println("Receiver:" + hello);
        try {
            System.out.println(new String(hello, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

重新启动项目,并在RabbitMQ管理菜单重新发送消息:


猜你喜欢

转载自blog.csdn.net/qq_41969879/article/details/81015262