Springboot整合RabbitMQ消费者

pom 文件.

org.springframework.boot

spring-boot-starter-parent

2.0.3.RELEASE

UTF-8

UTF-8

1.8

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-amqp

com.alibaba

fastjson

1.2.16

org.apache.maven.plugins

maven-checkstyle-plugin

3.0.0

UTF-8

xml/google_checks.xml

org.springframework.boot

spring-boot-maven-plugin

application.properties

spring.rabbitmq.host=

spring.rabbitmq.port=

spring.rabbitmq.username=

spring.rabbitmq.password=

spring.rabbitmq.virtual-host=

spring.rabbitmq.connection-timeout=15000

spring.rabbitmq.listener.simple.acknowledge-mode=manual

spring.rabbitmq.listener.simple.concurrency=5

spring.rabbitmq.listener.simple.max-concurrency=10

rabbitmqConfig 

import org.springframework.amqp.core.AcknowledgeMode;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;

import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class RabbitConfig {

/**

    * 初始化监听器

    * @param connectionFactory

    * @return

    */

    @Bean

    public SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory){

SimpleMessageListenerContainer simpleMessageListenerContainer =new SimpleMessageListenerContainer();

simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);

simpleMessageListenerContainer.setConnectionFactory(connectionFactory);

return simpleMessageListenerContainer;

}

}

RabbitReceiver  监听

import org.springframework.amqp.core.Message;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;

import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;

import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

@Component

public class RabbitReceiver {

@RabbitListener(queues = {"queue-1"})

@RabbitHandler

  public void onMessage(Message message, Channel channel)throws Exception {

Jackson2JsonMessageConverter jackson2JsonMessageConverter =new Jackson2JsonMessageConverter();

Object object =  jackson2JsonMessageConverter.fromMessage(message);

channel.basicQos(1);

System.out.println(object);

System.out.println("消费端Payload: " +  message.getBody());

Long deliveryTag = message.getMessageProperties().getDeliveryTag();

//手工ACK

      System.out.println(deliveryTag);

channel.basicAck(deliveryTag,false);

}

}

跟上一篇整合成功 Springboot整合RabbitMQ生产者 自己填写properties的值 启动项目应该完美运行.

本文仅限本人小白学习参考,不足之处请大佬指正。

你可能感兴趣的:(Springboot整合RabbitMQ消费者)