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);
		}
	}

猜你喜欢

转载自blog.csdn.net/yang134679/article/details/92847224