今天看啥  ›  专栏  ›  客观开发者

Rabbit的使用(代码)

客观开发者  · 简书  ·  · 2021-03-15 14:18

主要从几种模块写代码。
理论和分析为啥用,省略
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 工作模式 下次分享




原文地址:访问原文地址
快照地址: 访问文章快照