rabbitmq实现定时任务 java代码
时间: 2023-07-11 15:45:13 浏览: 115
以下是一个使用 RabbitMQ 实现定时任务的 Java 代码示例:
```java
import com.rabbitmq.client.AMQP;
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 RabbitMQDelayTask {
private final static String EXCHANGE_NAME = "delayed";
private final static String QUEUE_NAME = "task_queue";
private final static String ROUTING_KEY = "";
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.exchangeDeclare(EXCHANGE_NAME, "x-delayed-message", true, false, null);
// 创建队列并绑定到延迟交换机上
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
String message = "Task message";
int delayTime = 5000; // 延迟时间为 5 秒
// 发送任务消息并设置延迟时间
AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
builder.headers(java.util.Collections.<String, Object>singletonMap("x-delay", delayTime));
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, builder.build(), message.getBytes("UTF-8"));
channel.close();
connection.close();
}
}
```
注意,以上代码仅为示例,实际使用时需要根据具体需求进行相应的修改。同时,需要添加 RabbitMQ 客户端依赖库,例如 amqp-client 库。
阅读全文