美文网首页
Rabbit的使用(代码)

Rabbit的使用(代码)

作者: 客观开发者 | 来源:发表于2021-03-15 14:18 被阅读0次

    主要从几种模块写代码。
    理论和分析为啥用,省略
    1,简单模式

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

    yml 配置

    spring:
     rabbitmq:
       host: 192.168.1.136
       port: 5672
       username: admin
       password: admin
       publisher-confirm: true
       publisher-returns: true
       virtual-host: /
    
    

    config 配置 里面代码

    
    import org.springframework.amqp.core.Queue;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /*启动http://localhost:15672/#/users
    * 使用的spring-boot-starter-amqp
    *
    * */
    
    @Configuration
    public class RabbitConfig {
    
        /**
         * mq 队列
         * @return
         */
        @Bean
        public Queue hello() {
            return new Queue("simple.hello");
        }
    
        /**
         * 发送
         * @return
         */
        @Bean
        public SimpleSender simpleSender(){
            return new SimpleSender();
        }
    
        /**
         * 接受
         * @return
         */
        @Bean
        public SimpleReceiver simpleReceiver(){
            return new SimpleReceiver();
        }
    }
    

    发送者

    
    public class SimpleSender {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSender.class);
    
        @Autowired
        private RabbitTemplate template;
    
        private static final String queueName="simple.hello";
    
        public void send() {
            String message = "Hello World!";
            this.template.convertAndSend(queueName, message);
            LOGGER.info(" [x] Sent '{}'", message);
        }
    
    }
    
    

    接受者

    @RabbitListener(queues = "simple.hello")
    public class SimpleReceiver {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SimpleReceiver.class);
    
        @RabbitHandler
        public void receive(String in) {
            LOGGER.info(" [x] Received '{}'", in);
        }
    
    }
    
    

    测试

    @Autowired
        private SimpleSender simpleSender;
    //    @ApiOperation("简单模式")
        @RequestMapping(value = "/simple", method = RequestMethod.GET)
        @ResponseBody
        public R simpleTest() {
            for (int i = 0; i < 10; i++) {
                simpleSender.send();
                ThreadUtil.sleep(1000);
            }
            return R.ok();
        }
    

    效果


    lib_update_app_top_bg.png Snipaste_2021-03-15_13-59-43.png

    2 工作模式 下次分享

    相关文章

      网友评论

          本文标题:Rabbit的使用(代码)

          本文链接:https://www.haomeiwen.com/subject/ifjkcltx.html