package
com.xx;
/**
* Created by chenjun on 2017/6/19.
*/
import
com.rabbitmq.client.ConnectionFactory;
import
com.rabbitmq.client.Connection;
import
com.rabbitmq.client.Channel;
import
java.io.IOException;
import
java.util.concurrent.TimeoutException;
public
class
SendMQ {
private
ParseConfig config =
new
ParseConfig();
public
void
sendByQueue(String queue, String Message)
throws
IOException {
try
{
ConnectionFactory factory =
new
ConnectionFactory();
factory.setHost(config.host);
factory.setUsername(config.userName);
factory.setPassword(config.password);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queue,
true
,
false
,
false
,
null
);
String message = Message;
channel.basicPublish(
""
, queue,
null
, message.getBytes());
System.out.println(
"[x] Send '"
+ message +
"'"
);
channel.close();
connection.close();
}
catch
(TimeoutException e) {
e.printStackTrace();
}
}
public
void
sendByExchange(String exchange, String routingKey, String type, String Message)
throws
IOException {
try
{
ConnectionFactory factory =
new
ConnectionFactory();
factory.setHost(config.host);
factory.setUsername(config.userName);
factory.setPassword(config.password);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchange, type,
true
);
String message = Message;
channel.basicPublish(exchange, routingKey,
null
, message.getBytes());
System.out.println(
"[x] Send '"
+ message +
"'"
);
channel.close();
connection.close();
}
catch
(TimeoutException e) {
e.printStackTrace();
}
}
public
static
void
main(String[] args)
throws
IOException {
SendMQ s =
new
SendMQ();
s.sendByExchange(s.config.assetExchange, s.config.assetRouteKey,
s.config.assetType,
"hello world"
);
}
}
ParseConfig 是一个配置文件读取类 ,MQ地址 用户名 密码从配置文件读取