什么都不必说--springboot集成rabbitmq

114 阅读1分钟
场景:消息中间件,对业务进行分离

1.安装 rabbitmq

brew install rabbitmq

安装完成后,将

export PATH=$PATH:/usr/local/sbin

添加到

~/.bash_profile

文件中

2.启动rabbitmq服务

rabbitmq-server

3.添加maven

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

4.添加配置

@Configuration
public class RabbitConfig {
    /**
     * test
     * @param connectionFactory
     * @return
     */
    @Bean
    public SimpleRabbitListenerContainerFactory testListenerContainer(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(connectionFactory);
        factory.setConnectionFactory();
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(5);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);//是否开启ACK模式
        return factory;
    }
}

5.添加接收者

@Component
public class TestReceiver {
    @RabbitListener(queues = "test" ,containerFactory = "testListenerContainer")
    public void receiveMessageTest(String test) throws InterruptedException {
        System.out.println("======处理信息======"+System.currentTimeMillis());
        Thread.sleep(10000l);
        System.out.println("TEST Receiver  : " + test+"===="+System.currentTimeMillis());
        System.out.println("======处理信息结束======"+System.currentTimeMillis());
    }
}

6.发送者

@Component
public class TestSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    public void send() {
        String context = "hello " + System.currentTimeMillis();
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("test", context);
    }
}