Java Code Examples for com.rabbitmq.client.Channel#queueDeclare()
The following examples show how to use
com.rabbitmq.client.Channel#queueDeclare() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NewTask.java From rabbitmq with GNU General Public License v2.0 | 6 votes |
public static void main(String[] argv) throws java.io.IOException, Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); // �ַ���Ϣ for(int i = 0 ; i < 5; i++){ String message = "Hello World! " + i; channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); } channel.close(); connection.close(); }
Example 2
Source File: RabbitConsumer.java From java-study with Apache License 2.0 | 6 votes |
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); // 打开连接和创建频道,与发送端一样 Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。 channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); // 创建队列消费者 QueueingConsumer consumer = new QueueingConsumer(channel); // 指定消费队列 channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { //消费者程序运行开着 如果生产者新增了数据会自动获取 Thread.sleep(500); // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println("'[x] Received '" + message ); } }
Example 3
Source File: MainControllerTest.java From IGUANA with GNU Affero General Public License v3.0 | 6 votes |
public static void sendEnd(String fileName) throws IOException, TimeoutException { Config.getInstance(fileName); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(COMMON.CORE2RP_QUEUE_NAME, false, false, false, null); Properties p = new Properties(); p.put(COMMON.EXPERIMENT_TASK_ID_KEY, "1/1/1"); p.put(COMMON.RECEIVE_DATA_END_KEY, "true"); send(channel, p); channel.close(); connection.close(); }
Example 4
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 6 votes |
public void consumer2() throws Exception { //1、获取连接 Connection connection =RabbitMqConnectionFactoy.getConnection(); //2、声明通道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了) channel.basicQos(1);//每次只从服务器取1个处理 //4、定义队列的消费者 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println("-->消费者2号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString()); channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false); }; channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> { }); }
Example 5
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 6 votes |
public void producer() throws Exception{ //1、获取连接 Connection connection = RabbitMqConnectionFactoy.getConnection(); //2、声明信道 Channel channel = connection.createChannel(); //3、声明(创建)队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //4、定义消息内容(发布多条消息) for(int i = 0 ; i < 10 ; i++){ String message = "hello rabbitmq "+i; //定义消息头 Map<String,Object> header=new HashMap<>(); header.put("i",i); BasicProperties bp=new BasicProperties.Builder().headers(header).build(); //5、发布消息 channel.basicPublish("",QUEUE_NAME,bp,message.getBytes()); System.out.println("[x] Sent'"+message+"'"); //模拟发送消息延时,便于演示多个消费者竞争接受消息 // Thread.sleep(i*10); } //6、关闭通道 channel.close(); //7、关闭连接 connection.close(); }
Example 6
Source File: ProducerExchangeConsumer_Fanout.java From util4j with Apache License 2.0 | 6 votes |
public void consumer1() throws Exception { //1、获取连接 Connection connection =RabbitMqConnectionFactoy.getConnection(); //2、声明通道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(QUEUE_NAME1, false, false, false, null); //绑定队列到交换机 channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, ""); //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了) //channel.basicQos(1);//每次处理1个 //4、定义队列的消费者 //定义消费者 DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body) throws IOException { //获取并转成String String message = new String(body, "UTF-8"); System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString()); channel.basicAck(envelope.getDeliveryTag(), false); } }; channel.basicConsume(QUEUE_NAME1, autoAck,consumer); }
Example 7
Source File: Worker.java From neo4j-mazerunner with Apache License 2.0 | 6 votes |
public static void sendMessage(String message) throws java.io.IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); channel.basicPublish( "", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close(); }
Example 8
Source File: ConsumerTest.java From IGUANA with GNU Affero General Public License v3.0 | 6 votes |
public void send(Properties p) throws IOException, TimeoutException{ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(COMMON.CORE2RP_QUEUE_NAME, false, false, false, null); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(p); oos.flush(); oos.close(); bos.close(); byte [] data = bos.toByteArray(); channel.basicPublish("", COMMON.CORE2RP_QUEUE_NAME, null, data); }
Example 9
Source File: MessageSubscriberFactory.java From Insights with Apache License 2.0 | 6 votes |
public void registerSubscriber(String routingKey, final EngineSubscriberResponseHandler responseHandler) throws Exception { Channel channel = connection.createChannel(); String queueName = routingKey.replace(".", "_"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, MessageConstants.EXCHANGE_NAME, routingKey); channel.basicQos(ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount()); responseHandler.setChannel(channel); log.debug("prefetchCount "+ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount() ); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { responseHandler.handleDelivery(consumerTag, envelope, properties, body); } }; channel.basicConsume(queueName, false, routingKey, consumer); }
Example 10
Source File: Consumer4DirectExchange.java From code with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(Constant.ip); connectionFactory.setPort(Constant.port); connectionFactory.setVirtualHost("/"); connectionFactory.setAutomaticRecoveryEnabled(true); connectionFactory.setNetworkRecoveryInterval(3000); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); //4 声明 String exchangeName = "test_direct_exchange"; String exchangeType = "direct"; String queueName = "test_direct_queue"; String routingKey = "test.direct"; //表示声明了一个交换机 channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null); //表示声明了一个队列 channel.queueDeclare(queueName, false, false, false, null); //建立一个绑定关系: channel.queueBind(queueName, exchangeName, routingKey); //durable 是否持久化消息 QueueingConsumer consumer = new QueueingConsumer(channel); //参数:队列名称、是否自动ACK、Consumer channel.basicConsume(queueName, true, consumer); //循环获取消息 while (true) { //获取消息,如果没有消息,这一步将会一直阻塞 Delivery delivery = consumer.nextDelivery(); String msg = new String(delivery.getBody()); System.out.println("收到消息:" + msg); } }
Example 11
Source File: Consumer4TopicExchange.java From code with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { ConnectionFactory connectionFactory = new ConnectionFactory() ; connectionFactory.setHost(Constant.ip); connectionFactory.setPort(Constant.port); connectionFactory.setVirtualHost("/"); connectionFactory.setAutomaticRecoveryEnabled(true); connectionFactory.setNetworkRecoveryInterval(3000); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); //4 声明 String exchangeName = "test_topic_exchange"; String exchangeType = "topic"; String queueName = "test_topic_queue"; String routingKey = "user.#"; //String routingKey = "user.*"; // 1 声明交换机 channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null); // 2 声明队列 channel.queueDeclare(queueName, false, false, false, null); // 3 建立交换机和队列的绑定关系: channel.queueBind(queueName, exchangeName, routingKey); //durable 是否持久化消息 QueueingConsumer consumer = new QueueingConsumer(channel); //参数:队列名称、是否自动ACK、Consumer channel.basicConsume(queueName, true, consumer); //循环获取消息 while(true){ //获取消息,如果没有消息,这一步将会一直阻塞 Delivery delivery = consumer.nextDelivery(); String msg = new String(delivery.getBody()); System.out.println("收到消息:" + msg); } }
Example 12
Source File: Consumer.java From code with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { //1 创建ConnectionFactory ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(Constant.ip); connectionFactory.setPort(Constant.port); connectionFactory.setVirtualHost("/"); //2 获取C onnection Connection connection = connectionFactory.newConnection(); //3 通过Connection创建一个新的Channel Channel channel = connection.createChannel(); String exchangeName = "test_confirm_exchange"; String routingKey = "confirm.#"; String queueName = "test_confirm_queue"; //4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key channel.exchangeDeclare(exchangeName, "topic", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); //5 创建消费者 QueueingConsumer queueingConsumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, queueingConsumer); while (true) { Delivery delivery = queueingConsumer.nextDelivery(); String msg = new String(delivery.getBody()); System.err.println("消费端: " + msg); } }
Example 13
Source File: NegativeQueuePurgeTest.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Test(description = "Test queue purge on a queue with consumers", expectedExceptions = IOException.class) public void deleteUsedQueue() throws Exception { String queueName = "NegativeQueuePurgeTestDeleteUsedQueue"; Channel channel = amqpConnection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); channel.basicConsume(queueName, new DefaultConsumer(channel)); channel.queuePurge(queueName); }
Example 14
Source File: BindingsRestApiTest.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Test(dataProvider = "bindingData") public void testCreateBindingWithFilters(String queueName, String bindingPattern) throws IOException, TimeoutException { Channel channel = amqpConnection.createChannel(); channel.queueDeclare(queueName, false, false, false, new HashMap<>()); String exchangeName = "amq.topic"; String filter = "CorrelationId = 'testId123'"; HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings"); ClientHelper.setAuthHeader(httpPost, username, password); BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern) .exchangeName(exchangeName) .filterExpression(filter); String payloadString = objectMapper.writeValueAsString(createRequest); StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); CloseableHttpResponse response = client.execute(httpPost); Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED); BindingCreateResponse responseMessage = HttpClientHelper.getResponseMessage(response, BindingCreateResponse.class); Assert.assertEquals(responseMessage.getMessage(), "Binding created."); HashMap<String, Object> arguments = new HashMap<>(); arguments.put(Binding.JMS_SELECTOR_ARGUMENT.toString(), filter); channel.queueUnbind(queueName, exchangeName, bindingPattern, arguments); channel.close(); }
Example 15
Source File: NegativeQueueDeleteTest.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Test(description = "Test queue auto delete", expectedExceptions = IOException.class) public void testQueueAutoDelete() throws Exception { Channel channel = amqpConnection.createChannel(); String queueName = "NegativeQueueDeleteTestTestQueueAutoDelete"; channel.queueDeclare(queueName, false, false, true, null); String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel)); channel.basicCancel(consumerTag); // This should throw an exception since the queue is auto deleted channel.queueDeclarePassive(queueName); }
Example 16
Source File: RabbitMqIO.java From beam with Apache License 2.0 | 5 votes |
@Setup public void setup() throws Exception { connectionHandler = new ConnectionHandler(spec.uri()); connectionHandler.start(); Channel channel = connectionHandler.getChannel(); if (spec.exchange() != null && spec.exchangeDeclare()) { channel.exchangeDeclare(spec.exchange(), spec.exchangeType()); } if (spec.queue() != null && spec.queueDeclare()) { channel.queueDeclare(spec.queue(), true, false, false, null); } }
Example 17
Source File: DefaultChannelFactory.java From rxrabbit with MIT License | 4 votes |
ConsumeChannelImpl( Channel delegate, String exchange, String routingKey,int hashCode, ChannelType channelType, DefaultChannelFactory factory) throws IOException { super(delegate, hashCode, channelType, factory); AMQP.Queue.DeclareOk q = delegate.queueDeclare(); delegate.queueBind(q.getQueue(), exchange, routingKey); this.queue = q.getQueue(); }
Example 18
Source File: Worker.java From neo4j-mazerunner with Apache License 2.0 | 4 votes |
public void doMain(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(this); // if you have a wider console, you could increase the value; // here 80 is also the default parser.setUsageWidth(80); try { // parse the arguments. parser.parseArgument(args); if(sparkMaster == "" || hadoopHdfs == "") throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>"); ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs); ConfigurationLoader.getInstance().setSparkHost(sparkMaster); ConfigurationLoader.getInstance().setAppName(sparkAppName); ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory); ConfigurationLoader.getInstance().setDriverHost(driverHost); ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost); } catch( CmdLineException e ) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker"+parser.printExample(ALL)); return; } ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); channel.basicQos(20); // Initialize spark context GraphProcessor.initializeSparkContext(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); // Deserialize message Gson gson = new Gson(); ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class); // Run PageRank GraphProcessor.processEdgeList(processorMessage); System.out.println(" [x] Done '" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
Example 19
Source File: Rabbit.java From eip with MIT License | 4 votes |
void makeQueue(Channel channel, String queueName) throws IOException { boolean durable = false; boolean exclusive = false; boolean autoDelete = false; channel.queueDeclare(queueName, durable, exclusive, autoDelete, null); }
Example 20
Source File: QueueDeclarer.java From rabbitmq-cdi with MIT License | 4 votes |
@Override public void declare(Channel channel, QueueDeclaration declaration) throws IOException { LOGGER.info("declaring queue {}", declaration.getQueueName()); channel.queueDeclare(declaration.getQueueName(), declaration.isDurable(), declaration.isExclusive(), declaration.isAutoDelete(), declaration.getArguments()); }