SpringBoot integration of RabbitMQ

Environment: SpringBoot2.0

<!-- Spring Boot RabbitMQ 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

yml Configuration

the Spring: 
    RabbitMQ: 
        Host: 127.0.0.1 
        Port: 5672 
        username: the Guest 
        password: the Guest 
        # turn sends a confirmation 
        #-Publisher Confirms: to true 
        # enable the sending of failure to return 
        # Publisher-returns A: to true 
        # open ACK 
        # listener.direct.acknowledge-the MODE : Manual 
        # listener.simple.acknowledge-the MODE: Manual
RabbitConfig
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
    //topic
    public static final String TOPIC_QUEUE1 = "topic.queue1";
    public static final String TOPIC_QUEUE2 = "topic.queue2";
    public static final String TOPIC_EXCHANGE = "topic.exchange";

    //fanout
    public static final String FANOUT_QUEUE1 = "fanout.queue1";
    public static final String FANOUT_QUEUE2 = "fanout.queue2";
    public static final String FANOUT_EXCHANGE = "fanout.exchange";

    //direct
    public static final String DIRECT_QUEUE1 = "direct.queue1";
    public static final String DIRECT_QUEUE2 ="direct.queue2" ;
    public static final String DIRECT_EXCHANGE = "direct.exchange";


    * /@return
     *
     *
     * Topic mode/ **
     
    @Bean
    public Queue topicQueue1() {
        return new Queue(TOPIC_QUEUE1);
    }

    @Bean
    public Queue topicQueue2() {
        return new Queue(TOPIC_QUEUE2);
    }

    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }

    @Bean
    public Binding topicBinding1() {
        return BindingBuilder.bind(topicQueue1()).to(topicExchange()).with("zns.message");
    }

    @Bean
    publicTopicBinding2 the Binding () {
         return BindingBuilder.bind (topicQueue2 ()) to (topicExchange ()) with ( "# ZnS.".. ); 
    } 


    / ** 
     * Fanout mode 
     * Fanout is the familiar broadcast mode or subscription model, All queue to send a message to Fanout switch, this switch are bound to receive this news. 
     * @Return 
     * / 
    @Bean 
    public Queue fanoutQueue1 () {
         return  new new Queue (FANOUT_QUEUE1); 
    } 

    @Bean 
    public Queue fanoutQueue2 () {
         return  new new Queue (FANOUT_QUEUE2); 
    } 

    @Bean 
    public FanoutExchange fanoutExchange () {
         return  new newFanoutExchange (FANOUT_EXCHANGE); 
    } 

    @Bean 
    public the Binding fanoutBinding1 () {
         return BindingBuilder.bind (fanoutQueue1 ()) to (fanoutExchange ());. 
    } 

    @Bean 
    public the Binding fanoutBinding2 () {
         return BindingBuilder.bind (fanoutQueue2 ()). to (fanoutExchange ()); 
    } 

    / ** 
     * Direct mode 
     * key message routing (routing key), and if the binding key Binding consistent switch will send a message to a corresponding queue. Routing keys exact match with the name of the queue 
     * @return 
     * / 
    @Bean 
    public Queue directQueue1 () {
         return  new new Queue (DIRECT_QUEUE1); 
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(DIRECT_EXCHANGE);
    }

    @Bean
    public Binding directBinding1() {
        return BindingBuilder.bind(directQueue1()).to(directExchange()).with("direct.pwl");
    }

}

 The occurrence of a message

import com.zns.admin.api.TestModel;
import com.zns.admin.api.ZNSAdminApiApplication;
import com.zns.admin.api.config.RabbitConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RabbitmqTest {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Test
    public void testTopic() throws Exception {
        TestModel data=new TestModel(1,"topic...");
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_EXCHANGE,"zns.message", data);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_EXCHANGE, "zns.lzc", data);
    }

    @Test
    public void testFanout() throws Exception {
        TestModel data=new TestModel(2,"fanout...");
        this.rabbitTemplate.convertAndSend(RabbitConfig.FANOUT_EXCHANGE, "", data);
    }

    @Test
    public void testDirect() throws Exception {
        TestModel data=new TestModel(3,"direct...");
        this.rabbitTemplate.convertAndSend(RabbitConfig.DIRECT_EXCHANGE, "direct.pwl", data);
    }
}

Receive messages

import com.zns.admin.api.config.RabbitConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqReceiver {
    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE1)
    public void receiveTopic1(TestModel data) {
        System.out.println("【receiveTopic1监听到消息】" + data.toString());
    }
    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE2)
    public void receiveTopic2(TestModel data) {
        System.out.println("【receiveTopic2监听到消息】" + data.toString());
    }

    @RabbitListener(queues = RabbitConfig.FANOUT_QUEUE1)
    public void receiveFanout1(TestModel data) {
        System.out.println("【receiveFanout1监听到消息】" + data.toString());
    }
    @RabbitListener(queues = RabbitConfig.FANOUT_QUEUE2)
    public void receiveFanout2(TestModel data) {
        System.out.println("【receiveFanout2监听到消息】" + data.toString());
    }

    @RabbitListener(queues = RabbitConfig.DIRECT_QUEUE1)
    public voidreceiveDirect1 (TestModel Data) { 
        System.out.println ( "listen to the message [receiveDirect1]" + data.toString ()); 
    } 
    @RabbitListener (Queues = RabbitConfig.DIRECT_QUEUE1)
     public  void receiveDirect2 (TestModel Data) { 
        the System.out. the println ( "listen to the message [receiveDirect2]" + data.toString ()); 
    } 

}

 

Acknowledgment ACK message to achieve

Open the relevant profile configuration switch

the Spring: 
    RabbitMQ: 
        Host: 127.0.0.1 
        Port: 5672 
        username: the Guest 
        password: the Guest 
        # turn sends an acknowledgment 
        Publisher -confirms: to true 
        # enable the sending of failure to return 
        Publisher -returns: to true 
        # open ACK 
        listener.direct.acknowledge - the MODE: Manual 
        listener .simple.acknowledge -mode: Manual

As used herein Fanout type of Exchange, for example, mainly to set the queue, switches and binding

@Configuration
public class RabbitMqFanoutACKConfig {

    @Bean
    public Queue ackQueue() {
        return new Queue("ackQueue");
    }

    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }

    @Bean
    Binding bindingAckQueue2Exchange(Queue ackQueue, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(ackQueue).to(fanoutExchange);
    }

}

Messaging Service

@Service
public class AckSenderService implements RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        System.out.println("AckSender returnedMessage " + message.toString() + " === " + i + " === " + s1 + " === " + s2);
    }

    /**
     * 消息发送
     */
    public void send() {
        final String content = "现在时间是" + LocalDateTime.now(ZoneId.systemDefault());

        //Set the return callback 
        rabbitTemplate.setReturnCallback ( the this );
         // set the callback acknowledgment 
        rabbitTemplate.setConfirmCallback ((correlationData, ACK, the cause is) -> {
             IF (ACK) { 
                System.out.println ( "message sent successfully!" ); 
            } 
            The else { 
                System.out.println ( "message transmission failure," the cause is + + correlationData.toString ()); 
            } 
        }); 
        rabbitTemplate.convertAndSend ( "ackQueue" , Content); 
    } 
}

Consumer news

@Component 
@RabbitListener (Queues = { "ackQueue" })
 public  class MyAckReceiver { 

    @RabbitHandler 
    public  void Process (String SENDMSG, Channel Channel, the Message Message) { 

        System.out.println ( "AckReceiver: Send message received" + sendMsg + "time receive the message" 
                + LocalDateTime.now (ZoneId.systemDefault ())); 

        the try {
             // tells the server to receive this message has been current consumer spending, you can delete the queue safety, so it will not back and then re-issued,
             // otherwise the message server that this message is not disposed of, follow-up will then send
             // the second parameter is the identifier for the message, false currently only confirm receipt of a message, true confirmation of all consumer get the message
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("process success");
        } catch (Exception e) {
            System.out.println("process fail");
            e.printStackTrace();
        }

    }
}

 Call senderService.send () test

Guess you like

Origin www.cnblogs.com/zengnansheng/p/11123234.html
Recommended