#centos9安装rabbitmq
rpm -ivh erlang-25.3.2-1.el9.x86_64.rpm
rpm -ivh rabbitmq-server-3.11.24-1.el8.noarch.rpm
yum install socat -y
#启动服务
service rabbitmq-server start
#启动网页管理界面
rabbitmq-plugins enable rabbitmq_management
#添加用户,设置角色
rabbitmqctl add_user admin admin
rabbitmqctl set_user_tags admin administrator
com.rabbitmq
amqp-client
5.9.0
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.115.152");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("admin");
factory.setVirtualHost("/memory");
try {
connection = factory.newConnection();
channel = connection.createChannel();
} catch (IOException | TimeoutException e) {
throw new RuntimeException(e);
}
String exchangeName = "ex.shop.orders";
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, true, null);
Map<String,Object> params = new HashMap<>();
params.put("x-queue-type","quorum");
String queueName = "queue.shop.stock";
channel.queueDeclare(queueName, true, false, false, params);
channel.queueBind(queueName, exchangeName, "");
channel.basicPublish("", queueName, MessageProperties.TEXT_PLAIN, "message".getBytes()) ;
channel.basicConsume(String queue, boolean autoAck, Consumer callback);
GetResponse response = channel.basicGet(QUEUE_NAME, boolean autoAck);
channel.close();
conection.clouse();
//Consumer完整案例
public static void main(String[] args) {
Connection connection = null;
Channel channel = null;
//1.首先创建连接,获取Channel
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.115.152");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("admin");
factory.setVirtualHost("/memory");
try {
connection = factory.newConnection();
channel = connection.createChannel();
} catch (IOException | TimeoutException e) {
throw new RuntimeException(e);
}
//声明queue
Map<String,Object> params = new HashMap<>();
params.put("x-queue-type","quorum");
String queueName = "queue.shop.stock";
//Consumer的队列定义需要与Publisher一致,或者先启动的程序定义一次。
try {
channel.queueDeclare(queueName, false, false, false, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
//定义回调函数处理业务
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
//System.out.println("调用业务代码实验" + R.ok(null));
System.out.println(" [x] Received '" + message + "'");
};
try {
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
队列直连
workers
fanout
direct
topic
org.springframework.boot
spring-boot-starter-amqp
spring.rabbitmq.*