rabbitMq与spring的整合

来源:互联网 发布:八字反推软件 编辑:程序博客网 时间:2024/05/17 06:07

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" />
  • 详细配置说明参见静态网页

创建发送服务

@Servicepublic 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;    }}

创建接受线程

@Servicepublic 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();    }
原创粉丝点击