springboot中使用rabbitmq路由模式

准备配置文件,按照springboot读取数据的key结构定义rabbitmq的连接信息

spring.rabbitmq.host=10.9.104.184
spring.rabbitmq.port=5672
spring.rabbitmq.username=easymall
spring.rabbitmq.password=123456
spring.rabbitmq.virtualHost=emvh

项目代码中声明我们可能用到的所有内容包括 队列,交换机,类型,路由key绑定等

	//定义声明所有的组件,交换机,队列queue,将
	//之间的关系绑定,完成一个路由模式
	@Bean
	public Queue queue(){
		return new Queue("springbootQ1", false, false, false);
	}
	
	//声明交换机,不同类型的交换机对应不同类
	@Bean
	public DirectExchange ex(){
		return new DirectExchange("springbootD1");
	}
	
	//路由绑定关系
	@Bean
	public Binding bind(){
		return BindingBuilder.bind(queue()).to(ex())
				.with("product.save");
	}

直接使用rabbitTemplate对象对rabbitmq进行消息发送生产者逻辑
(api比较多 converAndSend)
需求:http请求发送url,携带参数msg=“消息”,rk=“路由key”;
http://localhost/send?msg=消息&rk=product.update
利用rabbittemplate发送消息到交换机,携带路由key
接口文件
请求地址 http://localhost/send?msg=消息&rk=product.update
请求参数 msg消息,rk路由key
返回数据 生产端代码正常发送消息,可以返回success;

	@RestController
	public class MsgController {
		@Autowired
		private RabbitTemplate template;
		@RequestMapping("send")
		public String sendMsg(String msg,
				@RequestParam(value="rk")String routingKey){
			//调用rabbitTemplate发送消息 发送到交换机springbootD1
			template.convertAndSend("springbootD1", routingKey, msg);
			return "sucess";
		}
	}

消费者直接使用异步监听逻辑,使用注解完成
编写消费逻辑代码,在一个Component类中,实现@RabbitLisenter使用,作用在方法上,表示当前方法监听某个队列,在注解的属性中定义监听的队列(可以定义多个),消费逻辑代码在任意的工程系统中都可以编写(前提是系统支持访问生产端连接的同一个rabbitmq)

	@Component
	public class RabbitConsumer {
		//消费逻辑,接收到msg之后直接打印到控制台
		@RabbitListener(queues="springbootQ1")
		public void print(String msg){
			//msg就是消息
			System.out.println("消费者消费消息:"+msg);
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼鱼大头鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值