其他分享
首页 > 其他分享> > Rabbitmq简单使用

Rabbitmq简单使用

作者:互联网

yml的配置添加

  spring:
    rabbitmq:
      port: 5672
      host: 123.58.251.228
      username: guest
      password: guest
      virtual-host: admin

Rabbitmq的配置

  @Configuration
  public class MqConfig {

      public static final int DEFAULT_CONCURRENT = 2000;

      //声明队列
      @Bean("datacenter")
      public Queue directQueue(){
          return new Queue("datacenter",false); //队列名字,是否持久化
      }

      //声明交换机
      @Bean("DIRECT_EXCHANGE")
      public DirectExchange directExchange(){
          return new DirectExchange("exchange",false,false);//交换器名称、是否持久化、是否自动删除
      }

      //将队列绑定到交换机
      @Bean
      Binding binding1(@Qualifier("datacenter") Queue queue, @Qualifier("DIRECT_EXCHANGE") DirectExchange exchange){
          return BindingBuilder.bind(queue).to(exchange).with("datacenter");
      }

      //设置多线程接收
      @Bean("customContainerFactory")
      public SimpleRabbitListenerContainerFactory containerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer,
                                                                   ConnectionFactory connectionFactory) {
          SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
          factory.setConcurrentConsumers(10);
          factory.setMaxConcurrentConsumers(10);
          configurer.configure(factory, connectionFactory);
          return factory;
      }

  }

发送者

  @Component
  public class TradeSender {

      @Autowired
      AmqpTemplate rabbitmqTemplate;

      public void sendNewTrade(Integer i){
          String msg=String.valueOf(i);
          rabbitmqTemplate.convertAndSend("trade",msg);
      }
  }

接收者

  @RabbitListener(queues = "datacenter",containerFactory = "customContainerFactory")
  public class TradeReceiver {

      private static final Logger LOG = LoggerFactory.getLogger(TradeReceiver.class);

      @Autowired
      private volatile TradeService tradeService;

      @Autowired
      private Web3j web3j;


      @RabbitHandler
      public void handler(String msg) throws Exception {
          System.out.println(msg);
      }
  }

标签:datacenter,return,简单,factory,Rabbitmq,Bean,使用,msg,public
来源: https://www.cnblogs.com/foreversmile/p/14063086.html