本文将介绍rabbitmq在用java进行调用的代码实现
一、添加maven依赖
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>4.1.0</version> </dependency>
二、消息生产者
关键点如下:
1、创建ConnectionFactory,包括设置rabbitmq服务的地址与端口号(amqp默认端口是5672)、用户名、密码、vhost(默认是/) ;
2、获取Connection ;
3、获取Channel ,并在其上声明queue、exchanger,并通过routingkey把queue在exchanger进行绑定 ;
代码实例如下:
public class RabbitmqProducerMain { public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.0.107"); factory.setPort(5672); factory.setUsername("admin"); factory.setPassword("123456"); factory.setVirtualHost("vhostOne"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String queueName = "queueOne"; String exchangeName = "exchangerOne"; String routingKey = "queueOne"; channel.exchangeDeclare(exchangeName,"direct"); channel.queueDeclare(queueName,false,false,false,null); channel.queueBind(queueName,exchangeName,routingKey); int msgCnt =15000; while(msgCnt-->0){ String msg = "msg"+Math.random()*100; channel.basicPublish(exchangeName,routingKey,null,msg.getBytes()); //发送消息 System.out.println("produce msg :"+msg); TimeUnit.MILLISECONDS.sleep((long) (Math.random()*500)); } channel.close(); connection.close(); } }
三、消息消费者
关键点如下:
1、创建ConnectionFactory,包括设置rabbitmq服务的地址与端口号(amqp默认端口是5672)、用户名、密码、vhost(默认是/) ;
2、获取Connection ;
3、获取Channel ,并在其上声明queue ;
4、定义消费消息Consumer;
5、消费消息channel.basicConsume(queueName,false,"queueOne",consumer);
代码实例如下:
public class RabbitmqConsumerMain { public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.0.107"); factory.setPort(5672); factory.setUsername("admin"); factory.setPassword("123456"); factory.setVirtualHost("vhostOne"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String queueName = "queueOne"; channel.queueDeclare(queueName,false,false,false,null); channel.basicQos(5); //每次取5条消息 Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //消费消费 String msg = new String(body,"utf-8"); System.out.println("consume msg: "+msg); try { TimeUnit.MILLISECONDS.sleep((long) (Math.random()*500)); } catch (InterruptedException e) { e.printStackTrace(); } //手动消息确认 getChannel().basicAck(envelope.getDeliveryTag(),false); } }; //调用消费消息 channel.basicConsume(queueName,false,"queueOne",consumer); } }