springboot下rabbitmq的简单使用

这篇文章中介绍了如何安装rabbitmq,以及注意事项。

https://blog.csdn.net/qq_27224549/article/details/92084129

1.pom中添加相关的starter依赖。

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

2.配置文件中加入相关配置信息

#rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin

3.队列的简单使用。

先创建一个队列。然后创建一个队列的发送者(生产者)。在创建队列的接收者(消费者)。

创建队列

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.Queue;
@Configuration
public class RabbitConfig {
	    @Bean
	    public Queue Queue() {        
	        return new Queue("hello");
	    }

}

生产者

import java.util.Date;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class HelloSender {
	@Autowired
    private AmqpTemplate rabbitTemplate;    
    
    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);        
        this.rabbitTemplate.convertAndSend("hello", context);
    }
}

消费者

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {
	@RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }
}

测试

在Controller中注入生产者,直接调用send方法即可。

@RequestMapping("/hello")    
    public String index() { 
		helloSender.send();
        return "Hello World";
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值