rabbitMq與spring的整合

rabbitMq與spring的整合

  • 本文所涉及字符串均可用ioc注入,只是我懶得寫……

添加mvn庫

<dependency>  
    <groupId>org.springframework.amqp</groupId>  
    <artifactId>spring-rabbit</artifactId>  
    <version>1.3.5.RELEASE</version>  
</dependency> 

添加connectionFactory的bean

<rabbit:connection-factory id="connectionFactory" host="localhost" publisher-confirms="true" virtual-host="/" username="admin"
        password="admin" />
  • 詳細配置說明參見靜態網頁

創建發送服務

@Service
public class SendService {
    private static final String EXCHANGE_NAME = "topic_logs";
    @Autowired//這裏注入了工廠
    private ConnectionFactory connectionFactory;

    public void sendMessage() throws IOException, TimeoutException {
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, "topic");
            // 待發送的消息
            String[] routingKeys = new String[] { "quick.blue.rabbit", "quick.red.rabbit" };
            // 發送消息
            for (String severity : routingKeys) {
                String message = "From " + severity + " routingKey' s message!";
                channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
                System.out.println("TopicSend  Sent '" + severity + "':'" + message + "'");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();//必須關閉connection,來結束髮送線程
            }
        }
    }

    public ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

}

創建接受線程

@Service
public class RedListener implements Runnable {//另開線程監聽隊列
    private static final String EXCHANGE_NAME = "topic_logs";
    @Autowired//注入工廠
    private ConnectionFactory connectionFactory;

    @Override
    public void run() {//線程主方法
        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, "topic");
            String queueName = channel.queueDeclare().getQueue();
            // 路由關鍵字
            String[] routingKeys = new String[] { "*.red.*" };
            // 綁定路由關鍵字
            for (String bindingKey : routingKeys) {
                channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
                System.out.println("redTopic exchange:" + EXCHANGE_NAME + ", queue:" +                              queueName + ", BindRoutingKey:"+ bindingKey);
            }

            System.out.println("red [*] Waiting for messages. To exit press CTRL+C");

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,                                   AMQP.BasicProperties properties,byte[] body) throws IOException {
                            String message = new String(body, "UTF-8");
                            System.out.println("red  Received '" + envelope.getRoutingKey() +                               "':'" + message + "'");
                }
            };
            channel.basicConsume(queueName, true, consumer);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }
}

主線程

public static void main(String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        BlueListener blueListener = ctx.getBean(BlueListener.class);
        blueListener.run();
        RedListener redListener = ctx.getBean(RedListener.class);
        redListener.run();
        SendService send = ctx.getBean(SendService.class);
        send.sendMessage();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章