文件名:rabbitmq-client.jar
下载地址:http://download.csdn.net/detail/monkey131499/9440572
下载后将文件导入到项目中。
import java.io.IOException; import java.util.concurrent.TimeoutException; import org.apache.log4j.Logger; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * send message * @author monkey * */ public class Send {//发送端 private final static String QUEUE_NAME = "queue_test_1"; static Logger logger = Logger.getLogger(Send.class); public static void start() throws IOException, TimeoutException { //connection制造工厂 ConnectionFactory factory = new ConnectionFactory(); //由于rabbitmq-server安装在本机,故用localhost或127.0.0.1 factory.setHost("localhost"); //创建连接 Connection connection = factory.newConnection(); //创建渠道 Channel channel = connection.createChannel(); //定义queue属性 channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "This is the test message~"; //发送消息 channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); logger.info(" [*] Send '" + message + "' to "+QUEUE_NAME+" success!" ); channel.close(); connection.close(); } }
import org.apache.log4j.Logger; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.GetResponse; /** * receive message * @author monkey * */ public class Receive {//接收端 //定义queue名称 private final static String QUEUE_NAME = "queue_test_1"; //设置日志 static Logger logger = Logger.getLogger(Receive.class); public static void start() throws Exception { //connection制造工厂 ConnectionFactory factory = new ConnectionFactory(); //由于rabbitmq-server安装在本机,故用localhost或127.0.0.1 factory.setHost("localhost"); //创建连接 Connection connection = factory.newConnection(); //创建渠道 Channel channel = connection.createChannel(); //定义queue属性 channel.queueDeclare(QUEUE_NAME, false, false, false, null); // logger.info("[*] Waiting for messages. To exit press CTRL+C"); boolean noAck = false; GetResponse response = channel.basicGet(QUEUE_NAME, noAck); if (response == null) { logger.info("[*] Waiting for messages. To exit press CTRL+C"); } else { byte[] body = response.getBody(); long deliveryTag = response.getEnvelope().getDeliveryTag(); String message = new String(body); logger.info("[**] Received '" + message + "' from "+QUEUE_NAME); channel.basicAck(deliveryTag, false); // acknowledge receipt of the message } channel.close(); connection.close(); } }
/** * main * @author monkey * */ public class Main { public static void main(String[] args) throws Exception { int num=10000; int i=0; while(i<num){ Send.start(); Receive.start(); i++; } } }