--- RabbitMQ messaging middleware started 3 --- integration with SpringMVC

The second we briefly introduce RabbitMQ and integration with SpringMVC:

As part of the project has not yet switched SpringBoot, so here introduce and integrate RabbitMQ and the SpringMVC.

1, write a message producer

  (1) pom document incorporated RabbitMQ its dependencies

 <dependency>
      <groupId>org.springframework.amqp</groupId>
      <artifactId>spring-rabbit</artifactId>
      <version>${rabbitmq.version}</version>
 </dependency>

  (2) class configuration write RabbitMQ

//连接rabbitMQ的基本配置
@Configuration
@EnableRabbit
public class RabbitConfig {

	@Bean
	public ConnectionFactory connectionFactory() {
		// 读取rabbitmq配置,此处请自行配置,一般配置于配置文件
		String hostname = PropertiesUtils.GetPropertiesByClassPath("global.properties").getProperty("rabbit.hostname");
		String username = PropertiesUtils.GetPropertiesByClassPath("global.properties").getProperty("rabbit.username");
		String password = PropertiesUtils.GetPropertiesByClassPath("global.properties").getProperty("rabbit.password");
		int port = Integer.valueOf(PropertiesUtils.GetPropertiesByClassPath("global.properties").getProperty("rabbit.port"));;

		CachingConnectionFactory connectionFactory = new CachingConnectionFactory(hostname);
		connectionFactory.setUsername(username);
		connectionFactory.setPassword(password);
		connectionFactory.setPort(port);
		return connectionFactory;
	}

	@Bean
	public AmqpAdmin amqpAdmin() {
		return new RabbitAdmin(connectionFactory());
	}

	@Bean
	public RabbitTemplate rabbitTemplate() {
		return new RabbitTemplate(connectionFactory());
	}

	//配置消费者监听的容器
	@Bean
	public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
		SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
		factory.setConnectionFactory(connectionFactory());
		factory.setConcurrentConsumers(3);
		factory.setMaxConcurrentConsumers(10);
		return factory;
	}
	
	 @Bean
	    public Queue Queue() {
//	    	System.out.println("RabbitConfig");
	        return new Queue("orderInfoQueue");
	    }
}

  (3) the preparation of a producer-consumer model configuration class

//生产者消费者模式的配置,包括一个队列和两个对应的消费者
@Configuration
public class ProducerConsumerConfig {

	@Bean
	public Queue myQueue() {
	   Queue queue=new Queue("myqueue");
	   return queue;
	}
}

  (4) write message class

@Service
public class ProducerImpl implements Producer {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Override
	public void sendMessage(String queue, Message message) {
		if (queue.equals("error")) {
			throw new RuntimeException("error");
		}
		rabbitTemplate.setQueue(queue);
		rabbitTemplate.convertAndSend(queue,message);
	}

2, write a message consumers 

  (1) prepared by the same producer (1) is introduced dependence (2) to write configuration (3) Configuration Mode

  (2) write the received message type

public class Receiver {
    private final static String QUEUE_NAME = "MyQueue";

    public static void main(String[] args) {
        receive();
    }

    public static void receive()
    {
        ConnectionFactory factory = null;
        Connection connection = null;
        Channel channel = null;

        try {
            factory = new ConnectionFactory();
            factory.setHost("localhost");
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            Consumer consumer = new DefaultConsumer(channel){
                public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                                           byte[] body) throws IOException {
                    System.out.println("11111111111");
                    String message = new String(body, "UTF-8");
                    System.out.println("收到消息....."+message);
                }};
            channel.basicConsume(QUEUE_NAME, true,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            if (channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3, the test message is received 

So far, RabbitMQ and SpringMVC integration has been completed, I hope the next hands-on children's shoes.

 

Published 41 original articles · won praise 47 · views 30000 +

Guess you like

Origin blog.csdn.net/u014526891/article/details/87557635