文章目录
RabbitMQ-java-client版本
com.rabbitmq:amqp-client:4.3.0
RabbitMQ
版本声明: 3.6.15
API介绍
-
Connection Factory
、Connection
、Channel
都是RabbitMQ
对外提供的API中最基本的对象。Connection
是RabbitMQ
的socket连接,它封装了socket协议相关部分逻辑。Connection Factory
则是Connection
的制造工厂,Connection
是用来开启Channel
的,AMQP协议层面的操作是通过Channel
进行的。 -
代码示例
private Logger logger = LoggerFactory.getLogger("rabbitmq-producer"); @Test public void testDirectExchange(){ ConnectionFactory factory = new ConnectionFactory(); String userName = "jannal"; String password = "jannal"; String virtualHost = "jannal-vhost"; String queueName = "jannal.direct.queue"; String exchange = "jannal.direct.exchange"; String routingKey = "SMS"; String bindingKey = "SMS"; String hostName = "jannal.mac.com"; int portNumber = 5672; factory.setUsername(userName); factory.setPassword(password); factory.setVirtualHost(virtualHost); factory.setHost(hostName); factory.setPort(portNumber); //以上等价下面 //factory.setUri("amqp://jannal:jannal@jannal.mac.com:5672/jannal-vhost"); factory.setAutomaticRecoveryEnabled(false); Connection conn = null; try { //创建连接 conn = factory.newConnection(); //通过连接创建通道 Channel channel = conn.createChannel(); //持久化 boolean durable = true; //独占 boolean exclusive = false; //是否自动删除 boolean autoDelete = false; //声明队列 channel.queueDeclare(queueName, durable, exclusive, autoDelete, null); //声明交换器,direct交换器类型下,RoutingKey与BindingKey需要完全匹配 channel.exchangeDeclare(exchange, "direct", true); //绑定 channel.queueBind(queueName, exchange, bindingKey); //无法路由时,消息处理方式。true返回给Producer,false则直接丢弃消息