springboot整合RabbitMQ 消费端处理数据

pom 依赖

   		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

写一个rabbitmq配置文件

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableRabbit
public class RabbitMQConfig {



    /**
     * 注入交换机
     * @return
     */
    @Bean
    public FanoutExchange exchange1() {
        return new FanoutExchange ("自己的交换机");
    }

    /**
     * 注入队列
     * @return
     */
    @Bean
    public Queue queue1() {
        return new Queue("名字随便取");
    }

    /**
     * 交换机和队列绑定
     * @return
     */
    @Bean
    public Binding binding1() {
        return BindingBuilder.bind(queue1()).to(exchange1());
    }

消费者端代码

@Component
@Slf4j
public class MyConsumer {

	/**
	*   队列名和配置文件中队列名一样即可消费到
	**/
  @RabbitListener(queues = "名字随便取")
    public void handleMessage(Message message) {
        byte[] body = message.getBody();

        // 指定编码方式将字节数组转换为字符串
        String content = null; // 获取消息体字节数组
            content = new String(body, "GBK");
            System.out.println(content);
    }




}

你可能感兴趣的:(java-rabbitmq,spring,boot,rabbitmq)