阿里的
String s = ""; //发送的信息
ConnectionFactory factory = new ConnectionFactory();
// 设置接入点,到控制台概览页面上查看获取
factory.setHost("aliyuncs.com");
// ${UID} 为资源 Owner 账户 ID 信息,单击控制台右上角客户头像进入账号管理查看
// ${AccessKey} 阿里云身份验证,在阿里云服务器管理控制台创建
// ${SecretKey} 阿里云身份验证,在阿里云服务器管理控制台创建
//一定要这个才能自动恢复
factory.setCredentialsProvider(new AliyunCredentialsProvider(${AccessKey}, ${SecretKey}, ${UID}));
factory.setAutomaticRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(5000);
// 设置 Vhost 名称,请确保已在控制台上创建完成
factory.setVirtualHost("VhostName");
// 默认端口,非加密端口 5672,加密端口 5671
factory.setPort(5672);
//基于网络环境合理设置超时时间
factory.setConnectionTimeout(30 * 1000);
factory.setHandshakeTimeout(30 * 1000);
factory.setShutdownTimeout(0);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//设置exchangeType
channel.exchangeDeclare("ex_live_msg", "fanout",true,false,null);
// 开始发送消息
// ${ExchangeName} 必须在控制台上已存在,并且 Exchange 的类型与控制台上的类型一致
// BindingKey 根据业务需求填入相应的 BindingKey
channel.basicPublish("ex_live_msg", "down", true, null,
s.getBytes(StandardCharsets.UTF_8));
connection.close();
常规的
String s = ""; //发送的信息
String QUEUE_NAME = "down";
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("ip");
factory.setPort(5672);
//基于网络环境合理设置超时时间
factory.setConnectionTimeout(30 * 1000);
factory.setHandshakeTimeout(30 * 1000);
factory.setShutdownTimeout(0);
factory.setVirtualHost("real_time");
factory.setUsername("userName");
factory.setPassword("password");
Connection connection = null;
Channel channel = null;
try {
//1.创建连接和通道
connection = factory.newConnection();
channel = connection.createChannel();
//设置exchangeType
channel.exchangeDeclare("ex_live_msg", "fanout",true,false,null);
//3.发布消息
channel.basicPublish("ex_live_msg", "down", true, null,s.getBytes());
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
//4.关闭连接
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}