rabbitmq多线程并发消费

1.消费者
channel.basicQos(consumer.getEndpoint().getPrefetchSize(), consumer.getEndpoint().getPrefetchCount(),
consumer.getEndpoint().isPrefetchGlobal());

public class Consumer {

    private final static String QUEUE_NAME = MQConfig.MOMENTS_QUEUE; //队列名称

    public static void main(String[] args) {
        initModule();
    }

    public static void initModule() {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1"); //设置rabbitmq-server的地址
        connectionFactory.setPort(5672);  //使用的端口号
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        //由连接工厂创建连接
        Connection connection = null;

        try {
            connection = connectionFactory.newConnection();
            //通过连接创建信道
            final Channel channel = connection.createChannel();
            channel.basicQos(0, 3, true);
            //创建消费者,指定要使用的channel。QueueingConsume类已经弃用,使用DefaultConsumer代替
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                //监听的queue中有消息进来时,会自动调用此方法来处理消息。但此方法默认是空的,需要重写
                @Override
                public void handleDelivery(java.lang.String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    MqMessageDispatcher.doDispatch(new String(body, "UTF-8"), channel, envelope);
                }
            };

            //监听指定的queue。会一直监听。
            //参数:要监听的queue、是否自动确认消息、使用的Consumer
            channel.basicConsume(QUEUE_NAME, false, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}


2.线程消费

public class MqMessageDispatcher {

	public static Logger logger = LoggerFactory.getLogger(MqMessageDispatcher.class);

	public static ExecutorService msgHandleService = Executors.newFixedThreadPool(2);

	static {
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				msgHandleService.shutdown();
			}
		});

	}

	public static void doDispatch(String message, Channel channel, Envelope envelope) {
		msgHandleService.execute(new MessageHandleTask(message, channel, envelope));
	}

	private static class MessageHandleTask implements Runnable {

		String message;
		Channel channel;
		Envelope envelope;

		public MessageHandleTask(String message, Channel channel, Envelope envelope) {
			this.message = message;
			this.channel = channel;
			this.envelope = envelope;
		}

		@Override
		public void run() {
			long start = System.currentTimeMillis();
			logger.info("Received message: " + message);
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				// 手动确认消息,若自动确认则不需要写以下该行
				channel.basicAck(envelope.getDeliveryTag(), false);
			} catch (IOException e) {
				System.err.println("fail to confirm message:" + message);
			}
		}
	}


}


3.mqconfig

@Configuration
public class MQConfig {

    public static final String MOMENTS_EXCHANGE = "moments-exchange";
    public static final String MOMENTS_QUEUE = "moments-queue";

    @Bean
    public Queue momentsQueue() {
        Map<String, Object> arguments = new HashMap<>();
        Queue queue = new Queue(MOMENTS_QUEUE,true, false, false,arguments);
        return queue;
    }

    @Bean
    public FanoutExchange momentsExchange() {
        return new FanoutExchange(MOMENTS_EXCHANGE);
    }

    @Bean
    public Binding MomentsBinding() {
        return BindingBuilder.bind(momentsQueue()).to(momentsExchange());
    }


}

4.生产者

@Component
public class Sender {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public void sendMessage(JSONObject message) {
        System.out.println("推送消息:" + JSON.toJSONString(message));
        // 1. 指定交换机;
        // 2. 配置文件中没有设置 绑定key,不需要指定;
        // 3. 发送的消息
        rabbitTemplate.convertAndSend(MQConfig.MOMENTS_EXCHANGE, "", message);
    }

    public void sendMessage(String message) {
        System.out.println("推送消息:" + message);
        // 1. 指定交换机;
        // 2. 配置文件中没有设置 绑定key,不需要指定;
        // 3. 发送的消息
        rabbitTemplate.convertAndSend(MQConfig.MOMENTS_EXCHANGE, "", message);
    }

}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lxy000001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值