Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

List of usage examples for com.rabbitmq.client ConnectionFactory ConnectionFactory

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

From source file:SendMessage.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);
    String message = "Message 004!";

    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*from w  w w . j  a  v  a2 s  .  c  o m*/
    connection.close();
}

From source file:Process.java

public void procesar() {
    System.out.println("Paso2");
    ConnectionFactory factory = new ConnectionFactory();
    try {//from   w  w w .  ja  v  a2 s  .c  o  m
        System.out.println("Paso3");
        factory.setUri(uri);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("hello", true, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String mensaje = new String(delivery.getBody());
            System.out.println(" [x] Received '" + mensaje + "'");
            System.out.println("Procesando..." + mensaje + "-" + Calendar.getInstance());
            PlanPago pp = dao.leer(new Long(mensaje));
            if (pp.getLinea() != null) {
                //generar cuota
                List<Cuota> cuotas = aa.generarCuotas(pp.getValor(), pp.getLinea().getTasa(), pp.getPlazo());
                pp.setCuotas(cuotas);
                //calcular nivel de riesgo
                pp.setNivelRiesgo(calcularNivelRiesgo());
                pp.setEstado("Generado");
                //guardar cuota
                dao.actualizar(pp);
                for (Cuota c : pp.getCuotas()) {
                    c.setIdPlan(pp.getId());
                }
                dao2.insertar(pp.getCuotas());
            }
            System.out.println("Finalizo " + mensaje + "-" + Calendar.getInstance());

        }

    } catch (URISyntaxException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    }

    //listenerContainer.setConnectionFactory(rabbitConnectionFactory);
    //listenerContainer.setQueueNames(rabbitQueue.getName());

    // set the callback for message handling
    /*listenerContainer.setMessageListener(new MessageListener() {
    public void onMessage(Message message) {
        final String mensaje = (String) messageConverter.fromMessage(message);
                
        // simply printing out the operation, but expensive computation could happen here
        System.out.println("Received from RabbitMQ: " + mensaje);
                
    }
    });
            
    // set a simple error handler
    /*listenerContainer.setErrorHandler(new ErrorHandler() {
    public void handleError(Throwable t) {
        t.printStackTrace();
    }
    });
            
    // register a shutdown hook with the JVM
    Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Shutting down BigOperationWorker");
        listenerContainer.shutdown();
    }
    });
            
    // start up the listener. this will block until JVM is killed.
    listenerContainer.start();
    System.out.println("BigOperationWorker started");
        */

}

From source file:Rece.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, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//from w w w.j  av a  2  s  . c  om
        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:RecieveMessage.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
        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 + "'");
        }/*  ww  w.  j  a va  2 s  .  co  m*/
    };
    channel.basicConsume(QUEUE_NAME, true, consumer);
}

From source file:TestUfms.java

public static void main(String[] args) throws Exception {
    // AMQP//from   ww w . j a  v a  2  s  .c om

    //      UfmsProto.RegCompany.Builder builderRegCompany = UfmsProto.RegCompany.newBuilder();
    //      builderRegCompany.setAddress("11-chaulong");
    //      builderRegCompany.setCompany("CPR_0101885631");
    //      builderRegCompany.setName("cadpro");
    //      builderRegCompany.setTel("0437152984");      
    //      UfmsProto.RegCompany rc = builderRegCompany.build();
    //      UfmsProto.BaseMessage rcMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegCompany).setExtension(UfmsProto.RegCompany.msg, rc).build();      
    //      byte[] rcData = rcMsg.toByteArray();
    //      System.out.println(rcMsg.toString());
    //      
    //      
    //      UfmsProto.RegDriver.Builder builderRegDriver = UfmsProto.RegDriver.newBuilder();
    //      builderRegDriver.setDatetimeExpire(1981979234);
    //      builderRegDriver.setDatetimeIssue(1095379200);
    //      builderRegDriver.setDriver("CPR_010099045659");
    //      builderRegDriver.setLicense("B2");
    //      builderRegDriver.setName("Dao Duy Hung");
    //      builderRegDriver.setRegPlace("Ha Noi");
    //      UfmsProto.RegDriver rd = builderRegDriver.build();
    //      UfmsProto.BaseMessage rdMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegDriver).setExtension(UfmsProto.RegDriver.msg, rd).build();      
    //      byte[] rdData = rdMsg.toByteArray();
    //      System.out.println(rdMsg.toString());
    //      
    //      UfmsProto.RegVehicle.Builder builderRegVehicle = UfmsProto.RegVehicle.newBuilder();
    //      builderRegVehicle.setCompany("CPR_0101885631");
    //      builderRegVehicle.setDatetime(1481979234);
    //      builderRegVehicle.setDeviceId("CPR_01");
    //      builderRegVehicle.setDeviceModel("CPR_Model_1");
    //      builderRegVehicle.setDeviceModelNo(1);
    //      builderRegVehicle.setDriver("CPR_010099045659");
    //      builderRegVehicle.setSim("0966871864");
    //      builderRegVehicle.setVehicle("29A1511");
    //      builderRegVehicle.setVehicleType(VehicleType.HopDong);
    //      builderRegVehicle.setVin("01");
    //      UfmsProto.RegVehicle rv = builderRegVehicle.build();
    //      UfmsProto.BaseMessage rvMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegVehicle).setExtension(UfmsProto.RegVehicle.msg, rv).build();      
    //      byte[] rvData = rvMsg.toByteArray();
    //      System.out.println(rvMsg.toString());

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("27.118.27.118");
    factory.setUsername("ctchaulong");
    factory.setPassword("EHjt81_FI");
    factory.setPort(5673);

    factory.setConnectionTimeout(600);

    Connection connection = factory.newConnection();
    System.out.println("creat connection done!");
    Channel channel = connection.createChannel();
    System.out.println("creat channel done!");

    int i = 0;
    // build WayPoint message 
    boolean a = true;
    while (a) {
        i++;

        UfmsProto.WayPoint.Builder builder = UfmsProto.WayPoint.newBuilder();
        int now = (int) (System.currentTimeMillis() / 1000);
        builder.setDatetime(now);
        builder.setDoor(true);
        builder.setDriver("010099045659");
        builder.setHeading(90);
        builder.setIgnition(true);
        builder.setSpeed(0); //<200
        //builder.setVehicle("29A1511");
        builder.setVehicle("29A1516");
        //builder.setVehicle("29K-8942");
        builder.setX(105.8445795); //> 0
        builder.setY(21.0306089); //>0
        //         builder.setX(021.0306089); //>0
        //         builder.setY(105.8445795); //> 0         
        builder.setZ(20); //>0            21.0306089,105.8445795,16z

        UfmsProto.WayPoint wp = builder.build();
        UfmsProto.BaseMessage msg = UfmsProto.BaseMessage.newBuilder()
                .setMsgType(UfmsProto.BaseMessage.MsgType.WayPoint).setExtension(UfmsProto.WayPoint.msg, wp)
                .build();
        byte[] data = msg.toByteArray();
        System.out.println(msg.toString());

        // send to server
        //channel.basicPublish("ufms.all", "", null, data);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rcData);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rdData);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rvData);   

        channel.basicPublish("tracking.ctchaulong", "track1", null, data);
        try {
            System.out.println("Send [" + i + "] time(s)! sleep in 1s...");
            Thread.sleep(1000); //1000 milliseconds is one second.
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

    }
    // clean up
    channel.close();
    connection.close();
    //      System.out.println("send done! ");
}

From source file:ThreadWorkers.java

public void run() {
    System.out.println("MyThread running");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = null;
    try {/*ww  w.j a v  a 2s.  c  o m*/
        connection = factory.newConnection();
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    try {
        channel.basicQos(1);
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }

    QueueingConsumer consumer = new QueueingConsumer(channel);
    try {
        channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumer.nextDelivery();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ShutdownSignalException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ConsumerCancelledException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        }
        String message = new String(delivery.getBody());

        System.out.println(" [x] Received '" + message + "'");
        try {

            doWork(message);
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(" [x] Done");

        try {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } catch (IOException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ThreadWorkers.java

private static String doWork(String task) throws InterruptedException, IOException {
    //for (char ch: task.toCharArray()) {
    //  if (ch == '.') Thread.sleep(1000);
    //}// www  .j a  va 2  s. co  m
    String result = "empty result";
    long threadId = Thread.currentThread().getId();
    System.out.println("in thread>>>>" + threadId);

    if (task.equalsIgnoreCase(""))
        return result;
    if (task == null)
        return result;
    //if(task.charAt(0)=='f' || task.charAt(0)=='1') return result;

    if (task.charAt(0) == 'f')
        result = "factorial of " + task.substring(1) + ">>" + factor(task.substring(1)).toString();
    else if (task.charAt(0) == 'p') {

        if (isPrime(task.substring(1).toString()))
            result = task.substring(1).toString() + " is prime";
        else
            result = task.substring(1).toString() + " is not prime";
    } else {
        result = "exponent " + task.substring(1) + ">>" + exp(task.substring(1)).toString();
    }
    // sending result
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_REPLY_NAME, true, false, false, null);
    //String[] msg= {"10","second",".........."};
    //String[] msg= {"1","second","."};
    //String message ="rvr";// getMessage(msg);

    channel.basicPublish("", TASK_QUEUE_REPLY_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, result.getBytes());
    System.out.println(" [x] Sent reply to client:: '" + result + "'");

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

    return result;
}

From source file:ReplyUtil.java

public void getReply() throws IOException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_REPLY_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);//w  ww.  java2 s. co  m

    QueueingConsumer consumer2 = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_REPLY_NAME, false, consumer2);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer2.nextDelivery();
        String message = new String(delivery.getBody());

        System.out.println(" [x] Receiving reply from worker::'" + message + "'");
        //doWork(message); 
        //System.out.println(" [x] Done" );

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

    }

}

From source file:RabbitMQConnector.java

License:Open Source License

@Override
boolean initialize(String IP, int Port, String[] args) {
    this.ip = IP;
    this.port = Port;
    if (args != null && args.length > 3) {
        rabbitUser = args[0];// w ww .  j ava  2 s .c o  m
        rabbitPass = args[1];
        queueName = args[2];
        vHost = args[3];
        factory = new ConnectionFactory();
        factory.setHost(this.ip);
        factory.setPort(this.port);
        factory.setUsername(rabbitUser);
        factory.setPassword(rabbitPass);
        factory.setVirtualHost(vHost);
    }
    return true;
}

From source file:SenderUtil.java

public void sendMessage(String msg) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    //String[] msg= {"10","second",".........."};
    //String[] msg= {"1","second","."};
    String message = msg;//getMessage(msg);

    channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*w w  w . j  av a  2s .  co  m*/
    connection.close();

}