package cn.tedu.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/*
主题模式
一个生产端 发送消息
一个消费端 监听队列 接收消息
*/
public class TopicMode {
private Channel channel;
@Before
public void init() throws IOException, TimeoutException {
//获取长连接,连接工厂获取
ConnectionFactory factory=new ConnectionFactory();
//提交一些参数
factory.setHost("192.168.123.128");
factory.setPort(5672);
factory.setUsername("username");
factory.setPassword("password");
factory.setVirtualHost("/");
//获取长连接
Connection conn = factory.newConnection();
channel=conn.createChannel();
}
private static final String type="topic";//必须是fanout
private static final String ex=type+"EX";
private static final String queue1="queue1"+type;
private static final String queue2="queue2"+type;
@Test
public void productor() throws IOException {
//客户端连接,声明所有组件 queue ex
channel.queueDeclare(queue1,false,false,false,null);
channel.queueDeclare(queue2,false,false,false,null);
//客户端声明自定义交换机
channel.exchangeDeclare(ex,type);//direct
//按照定义的同步发送逻辑.绑定队列到交换机
channel.queueBind(queue1,ex,"#.beijing.daxing");
channel.queueBind(queue1,ex,"*.beijing.*");
channel.queueBind(queue2,ex,"*.shanghai.*");
//将消息发送到交换机
channel.basicPublish(ex,"china.hangzhou.beifang.beijing.daxing",null,"hello 北京".getBytes());
//既然一个队列 可以绑定默认交换机,也可以绑定自定义的交换机
//说明一个队列可以使用不同的路由key去绑定多个交换机,
}
}
rabbitmq的主题模式测试代码
最新推荐文章于 2023-02-18 10:22:36 发布