1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import com.alibaba.nacos.common.utils.JacksonUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
@Slf4j public class RabbitMQUtil {
private static final AmqpAdmin amqpAdmin = SpringContextHolder.getBean(AmqpAdmin.class); private static final ConnectionFactory connectionFactory = SpringContextHolder.getBean(ConnectionFactory.class); private static final RabbitTemplate rabbitTemplate = SpringContextHolder.getBean(RabbitTemplate.class);
public static void createQueue(String queueName) { Queue queue = new Queue(queueName, true); amqpAdmin.declareQueue(queue); }
public static void deleteQueue(String queueName) { amqpAdmin.deleteQueue(queueName); }
public static void subscribeQueue(String queueName, Object messageListener, String methodName) { log.debug("subscribeQueue: {}", queueName); MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(messageListener, methodName); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames(queueName); container.setMessageListener(listenerAdapter); container.start(); }
public static void sendMessage(String queueName, Object message) { String json = JacksonUtils.toJson(message); log.debug("sendMessage, queueName: {} , message: {}", queueName, json); rabbitTemplate.convertAndSend(queueName, json); }
}
|