java中RabbitMQ的例子
时间: 2024-02-17 07:57:28 浏览: 68
java版本RabbitMQ实例.rar.rar
以下是Java中使用RabbitMQ的例子:
1. 使用Java原生代码调用RabbitMQ
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class RabbitMQExample {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
```
2. 使用spring-boot-starter-amqp调用RabbitMQ
首先需要在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
然后创建一个配置类RabbitConfig:
```java
@Configuration
public class RabbitConfig {
@Bean
public Queue TestDirectQueue() {
return new Queue("TestDirectQueue", true);
}
@Bean
DirectExchange TestDirectExchange() {
return new DirectExchange("TestDirectExchange");
}
@Bean
Binding bindingDirect() {
return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting");
}
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("localhost:5672");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
return connectionFactory;
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
return rabbitTemplate;
}
}
```
最后创建一个消费者类RbmqServiceImpl:
```java
@Service
public class RbmqServiceImpl implements RbmqService {
@Autowired
RabbitTemplate rabbitTemplate;
@RabbitListener(queues = "TestDirectQueue")
@Override
public void consumer(String msg) {
System.out.println("接受到的消息是:" + msg);
}
}
```
阅读全文