Java Code Examples for com.rabbitmq.client.Channel#exchangeDeclare()

The following examples show how to use com.rabbitmq.client.Channel#exchangeDeclare() . 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: Events.java    From rabbitmqexample with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {


        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Down Stream server ip (localhost):");
        String server_ip = br.readLine();
        if (server_ip.equalsIgnoreCase("")) {
            server_ip = "localhost";
        }

        ConnectionFactory factory_down = new ConnectionFactory();
        factory_down.setHost(server_ip);
        factory_down.setUsername("test");
        factory_down.setPassword("test");
        factory_down.setVirtualHost("poc");
        Connection connection_down = factory_down.newConnection();
        System.out.println("Connected to Down Stream node: " + server_ip);
        final Channel channel_down = connection_down.createChannel();
        final String exchange = "service";
        channel_down.exchangeDeclare(exchange, "topic", true);
        channel_down.basicPublish(exchange, "r1.gis", MessageProperties.PERSISTENT_BASIC, "better".getBytes());

    }
 
Example 2
Source File: CacheInvalidationSubscriber.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}
 
Example 3
Source File: MessagePublisherFactory.java    From Insights with Apache License 2.0 5 votes vote down vote up
public static void publish(String routingKey, Object data) throws Exception{
	ConnectionFactory factory = new ConnectionFactory();
       MessageQueueDataModel messageQueueConfig = ApplicationConfigProvider.getInstance().getMessageQueue();
	factory.setHost(messageQueueConfig.getHost());
       factory.setUsername(messageQueueConfig.getUser());
	factory.setPassword(messageQueueConfig.getPassword());
       Connection connection = factory.newConnection();
       Channel channel = connection.createChannel();
       channel.exchangeDeclare(MessageConstants.EXCHANGE_NAME, MessageConstants.EXCHANGE_TYPE);
       
       String message = new GsonBuilder().disableHtmlEscaping().create().toJson(data);
       channel.basicPublish(MessageConstants.EXCHANGE_NAME, routingKey, null, message.getBytes());
       connection.close();
}
 
Example 4
Source File: ExchangesRestApiTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test (dataProvider = "exchangeData")
public void testRetrieveAllExchanges(String exchangeName, String type) throws Exception {
    Channel channel = amqpConnection.createChannel();
    channel.exchangeDeclare(exchangeName, type);

    HttpGet httpGet = new HttpGet(apiBasePath + "/exchanges");
    ClientHelper.setAuthHeader(httpGet, username, password);
    CloseableHttpResponse response = client.execute(httpGet);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK, "Invalid status code");

    String responsePayloadString = EntityUtils.toString(response.getEntity());

    ExchangeMetadata[] exchanges = objectMapper.readValue(responsePayloadString, ExchangeMetadata[].class);
    Map<String, ExchangeMetadata> exchangeMetadataMap = new HashMap<>(exchanges.length);
    for (ExchangeMetadata exchange : exchanges) {
       exchangeMetadataMap.put(exchange.getName(), exchange);
    }

    validExchangeResponse(exchangeMetadataMap.get(exchangeName), exchangeName, type);

    String expectedExchangeName = "amq.direct";
    String expectedExchangeType = "direct";
    validExchangeResponse(exchangeMetadataMap.get(expectedExchangeName),
                          expectedExchangeName, expectedExchangeType);

    expectedExchangeName = "amq.topic";
    expectedExchangeType = "topic";
    validExchangeResponse(exchangeMetadataMap.get(expectedExchangeName),
                          expectedExchangeName, expectedExchangeType);

    channel.exchangeDelete(exchangeName, true);
    channel.close();

}
 
Example 5
Source File: TopicSend.java    From rabbitmq with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] argv) {
		Connection connection = null;
		Channel channel = null;
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");

			connection = factory.newConnection();
			channel = connection.createChannel();
//			����һ��ƥ��ģʽ�Ľ�����
			channel.exchangeDeclare(EXCHANGE_NAME, "topic");

			// �����͵���Ϣ
			String[] routingKeys = new String[]{"quick.orange.rabbit", 
												"lazy.orange.elephant", 
												"quick.orange.fox", 
												"lazy.brown.fox", 
												"quick.brown.fox", 
												"quick.orange.male.rabbit", 
												"lazy.orange.male.rabbit"};
//			������Ϣ
	        for(String severity :routingKeys){
	        	String message = "From "+severity+" routingKey' s message!";
	        	channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
	        	System.out.println("TopicSend [x] Sent '" + severity + "':'" + message + "'");
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception ignore) {
				}
			}
		}
	}
 
Example 6
Source File: ExchangeSender.java    From eip with MIT License 5 votes vote down vote up
public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    Rabbit rabbit = new Rabbit("localhost");
    Channel channel = rabbit.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    sendMessage(channel, EXCHANGE_NAME, "Widget", "Hello EIP Widget!");
    sendMessage(channel, EXCHANGE_NAME, "Gadget", "Hello EIP Gadget!");

    channel.close();
    rabbit.close();
}
 
Example 7
Source File: ChannelPoolListener.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void initialize(final Channel channel) throws IOException {
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    channel.exchangeDeclare("order", BuiltinExchangeType.DIRECT, true);
    channel.queueDeclare("registered-order", true, false, false, null);
    channel.queueBind("registered-order", "order", "registered-order");
}
 
Example 8
Source File: RabbitEventChannel.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
public RabbitEventChannel(EventMode mode, String name, Channel channel, ContentCodec codec) {
    super(mode, name);
    this.channel = channel;
    this.codec = codec;
    this.tags = new ConcurrentHashMap<>();
    try {
        channel.exchangeDeclare(name, BuiltinExchangeType.DIRECT);
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
}
 
Example 9
Source File: ClientMain.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
    LOG.info("Client Service starting ...");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:guest@localhost:15672/virtualHost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare("exchangeName", "direct", true);
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, "exchangeName", "publishKey");

    channel.close();
    connection.close();
}
 
Example 10
Source File: RabbitMQTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
private String createQueue(Channel channel) throws IOException {
    channel.exchangeDeclare(EXCHANGE_NAME, DIRECT_EXCHANGE, DURABLE);
    String queueName = UUID.randomUUID().toString();
    channel.queueDeclare(queueName, DURABLE, !EXCLUSIVE, AUTO_DELETE, NO_QUEUE_DECLARE_ARGUMENTS).getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);
    return queueName;
}
 
Example 11
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
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 12
Source File: RabbitMqBenchmarkDriver.java    From openmessaging-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<BenchmarkProducer> createProducer(String topic) {
    Channel channel = null;
    try {
        channel = connection.createChannel();
        channel.exchangeDeclare(topic, BuiltinExchangeType.FANOUT);
        channel.confirmSelect();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return CompletableFuture.completedFuture(new RabbitMqBenchmarkProducer(channel, topic, config.messagePersistence));
}
 
Example 13
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void producer() throws Exception{
	 //1、获取连接
    Connection connection = RabbitMqConnectionFactoy.getConnection();
    //2、声明信道
    Channel channel = connection.createChannel();
    //3、声明(创建)交换机
    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
    Thread.sleep(3000);
    //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、发布消息
        if(i%2!=0)
        {//单数进key1的队列
        	 channel.basicPublish(EXCHANGE_NAME,"test.a",bp,message.getBytes());
        }else
        {//偶数进key2的队列
        	 channel.basicPublish(EXCHANGE_NAME,"test.b",bp,message.getBytes());
        }
        System.out.println("[x] Sent'"+message+"'");
        //模拟发送消息延时,便于演示多个消费者竞争接受消息
        Thread.sleep(i*10);
    }
    //6、关闭通道
    channel.close();
    //7、关闭连接
    connection.close();
}
 
Example 14
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost(Constant.ip);
		connectionFactory.setPort(Constant.port);
		connectionFactory.setVirtualHost("/");
		
		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();
		
		// 这就是一个普通的交换机 和 队列 以及路由
		String exchangeName = "test_dlx_exchange";
		String queueName = "test_dlx_queue";
		String routingKey = "dlx.#";
		
		channel.exchangeDeclare(exchangeName, "topic", true, false, null);

		Map<String, Object> arguments = new HashMap<>();
		arguments.put("x-dead-letter-exchange", "dlx.exchange");
		//这个agruments属性,要设置到声明队列上
		channel.queueDeclare(queueName, true, false, false, arguments);
		channel.queueBind(queueName, exchangeName, routingKey);
		
		//要进行死信队列的声明:
		channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
		channel.queueDeclare("dlx.queue", true, false, false, null);
		channel.queueBind("dlx.queue", "dlx.exchange", "#");
		
		channel.basicConsume(queueName, true, new MyConsumer(channel));
		
		
	}
 
Example 15
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	Connection connection = connectionFactory.newConnection();
	Channel channel = connection.createChannel();
	
	
	String exchangeName = "test_qos_exchange";
	String queueName = "test_qos_queue";
	String routingKey = "qos.#";
	
	channel.exchangeDeclare(exchangeName, "topic", true, false, null);
	channel.queueDeclare(queueName, true, false, false, null);
	channel.queueBind(queueName, exchangeName, routingKey);
	
	/*
	 * prefetchSize:消息限制大小,一般为0,不做限制。
	 * prefetchCount:一次处理消息的个数,一般设置为1
	 * global:一般为false。true,在channel级别做限制;false,在consumer级别做限制
	 */
	channel.basicQos(0, 1, false);

	// 限流方式  第一件事就是 autoAck设置为 false
	channel.basicConsume(queueName, false, new MyConsumer(channel));
	
	
}
 
Example 16
Source File: RabbitMqUtils.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Declares the required exchanges for an application (only for agents).
 * @param domain the domain name
 * @param applicationName the application name
 * @param channel the RabbitMQ channel
 * @throws IOException if an error occurs
 */
public static void declareApplicationExchanges( String domain, String applicationName, Channel channel )
throws IOException {

	// "topic" is a keyword for RabbitMQ.
	if( applicationName != null ) {
		String exch = buildExchangeNameForAgent( domain, applicationName );
		channel.exchangeDeclare( exch, "topic" );
	}
}
 
Example 17
Source File: Configure.java    From rabbitmqexample with Apache License 2.0 4 votes vote down vote up
public static void init(Connection connection) throws Exception {
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(EXCHANGE_CHAT, BuiltinExchangeType.TOPIC, true);
    channel.close();
}
 
Example 18
Source File: RabbitMQTestRunner.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
void runPullTest() throws Exception {

        final String message = "hello rabbit mq";

        // producer side
        final Connection producerConnection = connectionFactory.newConnection();
        final Channel producerChannel = producerConnection.createChannel();

        producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
        producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PULL, false, false, false, null);
        producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PULL, RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL);

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
        producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, false, false, builder.appId("test").build(), message.getBytes());

        producerChannel.close();
        producerConnection.close();

        //comsumer side
        final Connection consumerConnection = connectionFactory.newConnection();
        final Channel consumerChannel = consumerConnection.createChannel();
        final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":" + consumerConnection.getPort();

        TestMessagePuller messagePuller = new TestMessagePuller(consumerChannel);
        Assert.assertEquals(message, messagePuller.pullMessage(MessageConverter.FOR_TEST, RabbitMQTestConstants.QUEUE_PULL, true));

        consumerChannel.close();
        consumerConnection.close();

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        // Wait till all traces are recorded (consumer traces are recorded from another thread)
        awaitAndVerifyTraceCount(verifier, 5, 5000L);

        verifier.printCache();
        // verify producer traces
        Class<?> producerChannelClass = producerChannel.getClass();
        Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
        ExpectedTrace channelBasicPublishTrace = Expectations.event(
                RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
                channelBasicPublish, // method
                null, // rpc
                remoteAddress, // endPoint
                "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
                Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
                Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
        ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
                RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
                "RabbitMQ Consumer Invocation", // method
                "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
                null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
                remoteAddress, // remoteAddress
                Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
        Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
        Method handleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand", AMQCommand.class);
        ExpectedTrace handleCompleteInboundCommandTrace = Expectations.event(
                RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
                handleCompleteInboundCommand); // method
        ExpectedTrace[] producerTraces = {channelBasicPublishTrace};
        ExpectedTrace[] consumerTraces = {rabbitMqConsumerInvocationTrace, handleCompleteInboundCommandTrace};
        verifier.verifyDiscreteTrace(producerTraces);
        verifier.verifyDiscreteTrace(consumerTraces);

        // verify consumer traces
        Class<?> consumerChannelClass = consumerChannel.getClass();
        Method channelBasicGet = consumerChannelClass.getDeclaredMethod("basicGet", String.class, boolean.class);
        ExpectedTrace channelBasicGetTrace = Expectations.event(
                RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
                channelBasicGet);
        Class<?> propagationMarkerClass = PropagationMarker.class;
        Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
        ExpectedTrace markTrace = Expectations.event(
                ServiceType.INTERNAL_METHOD.getName(),
                propagationMarkerMark);
        verifier.verifyDiscreteTrace(
                channelBasicGetTrace,
                markTrace);
        verifier.verifyTraceCount(0);
    }
 
Example 19
Source File: Consumer.java    From code with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	Connection connection = connectionFactory.newConnection();
	Channel channel = connection.createChannel();
	
	
	String exchangeName = "test_ack_exchange";
	String queueName = "test_ack_queue";
	String routingKey = "ack.#";
	
	channel.exchangeDeclare(exchangeName, "topic", true, false, null);
	channel.queueDeclare(queueName, true, false, false, null);
	channel.queueBind(queueName, exchangeName, routingKey);
	
	// 手工签收 必须要关闭 autoAck = false
	channel.basicConsume(queueName, false, new MyConsumer(channel));
	
	
}
 
Example 20
Source File: EmitLogDirect.java    From demo_springboot_rabbitmq with Apache License 2.0 3 votes vote down vote up
public static void send(String routingKey, String message) throws Exception {
    //1 建立channel
    Channel channel = ChannelUtils.getInstance();

    //2 声明交换机类型
    channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);

    //3 发送消息
    channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());


}