Example usage for com.rabbitmq.client Connection createChannel

List of usage examples for com.rabbitmq.client Connection createChannel

Introduction

In this page you can find the example usage for com.rabbitmq.client Connection createChannel.

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:com.project.finalproject.Recv.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    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");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override/*from w ww.j a v  a2 s.  c o  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(QUEUE_NAME, true, consumer);
}

From source file:com.project.finalproject.Send.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    try {//from  ww  w  .  j  a  va2 s  .  c o m
        InputStream is = new FileInputStream("hr.json");
        String jsontxt = IOUtils.toString(is);
        JSONObject jsonObject = new JSONObject(jsontxt);
        JSONArray stream = jsonObject.getJSONArray("stream");
        for (int i = 0; i < stream.length(); i++) {
            String message = stream.getJSONObject(i).getString("value");
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "'");
            TimeUnit.SECONDS.sleep(1);
        }
    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    channel.close();
    connection.close();
}

From source file:com.qt.core.util.MqConnectionUtil.java

License:Open Source License

public Channel getChannel(String key, String queueName, boolean durable) throws IOException {
    Connection connection = connectionMap.get(key);
    Channel channel = channelMap.get(key + queueName);
    if (channel == null || !channel.isOpen()) {
        channel = connection.createChannel();
        channel.queueDeclare(queueName, durable, false, false, null); // ???
        channelMap.put(key + queueName, channel);
    }/*w ww .  ja  v a 2  s.c  o m*/
    return channel;
}

From source file:com.service.OperationFacadeREST.java

@POST
@Override// w w  w.j  ava2  s .c om
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public void create(Operation entity) {
    if (!entity.getState().equals("waiting")) {
        super.create(entity);
        return;
    }
    if (entity.getOperationType())//venda
    {
        ArrayList<ClientStock> l = new ArrayList<>(getEntityManager()
                .find(Client.class, entity.getFkOwnerId().getClientId()).getClientStockCollection());
        Boolean fail = false;
        for (int i = 0; i < l.size(); i++) {
            if (l.get(i).getStock().equals(entity.getFkStockId())) {
                if (l.get(i).getQuantity() < entity.getQuantity())
                    return;
                l.get(i).setQuantity(l.get(i).getQuantity() - entity.getQuantity());
                getEntityManager().persist(l.get(i));
                entity.getFkOwnerId().setClientStockCollection(l);

                entity.setCreationDate(Date.from(Instant.now()));
                super.create(entity);
            }
        }
        if (fail)
            return;
    } else {
        entity.setCreationDate(Date.from(Instant.now()));
        if (entity.getFkStockId().getQuantity() > entity.getQuantity()) {

            System.out.println("yes");
            super.create(entity);
        } else {
            return;
        }
    }

    try {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("hello", false, false, false, null);
        System.out.println(super.findAll().get(super.findAll().size() - 1).getOperationId() + ","
                + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + ","
                + entity.getQuantity());

        String message = super.findAll().get(super.findAll().size() - 1).getOperationId() + ","
                + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + ","
                + entity.getQuantity();
        channel.basicPublish("", "hello", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        channel.close();
        connection.close();
    } catch (IOException ex) {
        Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TimeoutException ex) {
        Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.shopwiki.roger.event.MessageWorker.java

License:Apache License

/**
 * Call this to start consuming & handling messages.
 *///from ww  w . j  av  a  2 s .c  o  m
public void start() throws IOException {
    int numThreads = 1; // TODO: Parameterize this (will require multiple channels) ???
    Connection conn = null;
    try {
        conn = daemon ? connector.getDaemonConnection(numThreads) : connector.getConnection(numThreads);
        conn.addShutdownListener(reconnector);
        channel = conn.createChannel();

        MessageConsumer<T> consumer = new MessageConsumer<T>(handler, channel, queueArgs, route);
        consumer.start();
    } catch (IOException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (RuntimeException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (Error e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    }
}

From source file:com.shopwiki.roger.event.MessagingManager.java

License:Apache License

private static List<Channel> createChannels(Connection conn, int n) throws IOException {
    List<Channel> channels = Lists.newArrayList();
    for (int i = 0; i < n; i++) {
        Channel channel = conn.createChannel();
        channels.add(channel);/*from  w  ww .  j a  va  2  s  .c o m*/
    }
    return ImmutableList.copyOf(channels);
}

From source file:com.shopwiki.roger.example.ExampleEventHandler.java

License:Apache License

public static void main(String[] args) throws Exception {

    MessageHandler<String> handler = new MessageHandler<String>() {
        @Override// ww  w .j  av a2 s  .  co m
        public TypeReference<String> getMessageType() {
            return new TypeReference<String>() {
            };
        }

        @Override
        public void handleMessage(String name) {
            System.out.println("Hello " + name + "!");
        }
    };

    // Create the exchange if it doesn't exist.
    {
        Connection conn = connector.getConnection(1);
        Channel channel = conn.createChannel();
        channel.exchangeDeclare(route.exchange, "topic");
        conn.close();
    }

    boolean daemon = false;

    MessageWorker<String> worker = new MessageWorker<String>(connector, handler, route, daemon);
    worker.start();
}

From source file:com.shopwiki.roger.example.ExampleEventSender.java

License:Apache License

public static void main(String[] args) throws Exception {
    Connection conn = ExampleRpcServer.connector.getDaemonConnection(1);
    Channel channel = conn.createChannel();
    MessagingUtil.sendMessage(channel, ExampleEventHandler.route, "Robert");
}

From source file:com.shopwiki.roger.example.ExampleRpcClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    Connection conn = ExampleRpcServer.connector.getDaemonConnection(1);
    Channel channel = conn.createChannel();
    Route route = new Route("", "RpcExample_HelloWorld");
    Map<String, Object> queueArgs = null;

    TypeReference<Response> responseType = new TypeReference<Response>() {
    };/*  ww  w  .  j av  a 2s  .  c  o m*/
    RpcClient<Response> client = RpcClient.create(channel, route, queueArgs, responseType);

    Request request = new Request();
    request.name = "Robert";

    Future<RpcResponse<Response>> future = client.sendRequest(request);
    RpcResponse<Response> response = future.get(5, TimeUnit.SECONDS);

    System.out.println("HEADERS:\n" + response.getHeaders());
    System.out.println();
    System.out.println("BODY:\n" + MessagingUtil.prettyPrintMessage(response.getBody()));
}

From source file:com.shopwiki.roger.rpc.BasicWorkerFactory.java

License:Apache License

@Override
public RpcWorkers createWorkers(String queuePrefix) throws IOException {
    Connection conn = null;
    try {//  w  ww .j  a va  2  s.c  o  m
        conn = connector.getConnection(numThreads);

        List<Channel> channels = new ArrayList<Channel>();
        for (int i = 0; i < numThreads; i++) {
            Channel channel = conn.createChannel();
            channel.basicQos(1);
            channels.add(channel);
        }

        RpcWorkers workers = new RpcWorkers(conn);

        for (String procedureName : nameToHandler.keySet()) {
            RequestHandler<?, ?> handler = nameToHandler.get(procedureName);
            RpcWorker worker = new RpcWorker(handler, channels, queuePrefix, procedureName);
            workers.add(worker);
        }

        return workers;
        // TODO: Figure out a way to do this Exception handling outside of here ???
    } catch (IOException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (RuntimeException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (Error e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    }
}