RabbitMQ java操作

本文详细介绍了RabbitMQ的Java操作,包括Helloworld的基本消息模型、Work queues、订阅模型(Fanout、Direct、Topic)以及Springboot整合RabbitMQ。通过实例展示了如何创建生产者和消费者,以及消息确认机制、交换机类型和路由键的使用,最后讨论了页面静态化的概念和优势。
摘要由CSDN通过智能技术生成

RabbitMQ java操作

rabbitMQ提供了6种消息模型

img

Helloworld-基本消息模型(一对一)

img

搭建环境

创建maven工程 test-rabbitmq

pom加入RabbitMQ java client的依赖。

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
    <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <!--和springboot2.0.5对应-->
        <version>5.4.1</version>
    </dependency>
</dependencies>

util

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ConnectionUtil {
    /**
     * 建立与RabbitMQ的连接
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("127.0.0.1");
        //端口
        factory.setPort(5672);
        //设置账号信息,用户名、密码、vhost
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 通过工程获取连接
        Connection connection = factory.newConnection();
        return connection;
    }
}

测试

img

创建生产者

/**
 * 生产者
 */
public class Producter {
    //队列名称
    private static final String QUEUE = "helloword";

    public static void main(String[] args) throws Exception{
        Connection connection =null;
        //通道
        Channel channel = null;
        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建与Exchange的通道,每个连接可以创建多个通道,每个通道代表一个会话任务
            channel = connection.createChannel();
            /**
             * 声明队列,如果Rabbit中没有此队列将自动创建
             * param1:队列名称
             * param2:是否持久化
             * param3:队列是否独占此连接
             * param4:队列不再使用时是否自动删除此队列
             * param5:队列参数
             */
            channel.queueDeclare(QUEUE,true , false, false, null);
            //消息
            String message = "helloword!!!"+System.currentTimeMillis();
            /**
             * 消息发布方法
             * param1:Exchange的名称,如果没有指定,则使用Default Exchange
             * param2:routingKey(路由的key),消息的路由Key,是用于Exchange(交换机)将消息转发到指定的消息队列
             * param3:消息包含的属性
             * param4:消息体
             */
            /**
             * 这里没有指定交换机,消息将发送给默认交换机,每个队列也会绑定那个默认的交换机,但是不能显
             示绑定或解除绑定
             * 默认的交换机,routingKey等于队列名称
             */
            channel.basicPublish("", QUEUE,null , message.getBytes());
            System.out.println("Send Message is:'" + message + "'");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}

消费者

import com.rabbitmq.client.*;
import com.zhanglin.util.ConnectionUtil;

import java.io.IOException;

/**
 * 消费者
 */
public class Consumer {
    //队列名称
    private static final String QUEUE= "helloword";

    public static void main(String[] args) throws Exception{
        Connection connection = null;
        Channel channel = null;

        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建通道
            channel = connection.createChannel();
            //声明队列(队列名称,是否持久化,是否独占此连接,不使用时是否自动删除此队列,队列参数)
            channel.queueDeclare(QUEUE, true, false, false, null);
            //定义消费方法
            Channel finalChannel = channel;
            //匿名内部类
            DefaultConsumer consumer = new DefaultConsumer(finalChannel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //交换机
                    String exchange = envelope.getExchange();
                    //路由key
                    String routingKey = envelope.getRoutingKey();
                    //消息id
                    long deliveryTag = envelope.getDeliveryTag();
                    //消息内容
                    String msg = new String(body,"utf8");
                    System.out.println("receive message.." + msg);
                    //如果正常处理后需要做回复
                    finalChannel.basicAck(deliveryTag,false );
                }
            };
            /**
             * 监听队列:QUEUE 如果有消息来了,通过consumer来处理
             * 参数明细
             * 1、队列名称
             * 2、是否自动回复,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置
             为false则需要手动回复
             * 3、消费消息的方法,消费者接收到消息后调用此方法
             */
            channel.basicConsume(QUEUE,false ,consumer );
            //阻塞住,让他一直监听
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}

测试

img

img

我们发现,消费者已经获取了消息,但是程序没有停止,一直在监听队列中是否有新的消息。一旦有新的消息进入队列,就会立即打印.

消息确认机制(ACK)

通过刚才的案例可以看出,消息一旦被消费者接收,队列中的消息就会被删除。

那么问题来了:RabbitMQ怎么知道消息被接收了呢?

如果消费者领取消息后,还没执行操作就挂掉了呢?或者抛出了异常?消息消费失败,但是RabbitMQ无从得知,这样消息就丢失了!

因此,RabbitMQ有一个ACK机制。当消费者获取消息后,会向RabbitMQ发送回执ACK,告知消息已经被接收。不过这种回执ACK分两种情况:

- 自动ACK:消息一旦被接收,消费者自动发送ACK

- 手动ACK:消息接收后,不会发送ACK,需要手动调用

Work queues

img

work queues与入门程序相比,多了一个消费端,两个消费端共同消费同一个队列中的消息。

应用场景:对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。

生产者

睡眠一下就ok

img

消费者一个能力强,一个差

img

img

img

订阅模型分类

我们将会传递一个信息给多个消费者。 这种模式被称为“发布/订阅”。

1、1个生产者,多个消费者

2、每一个消费者都有自己的一个队列

3、生产者没有将消息直接发送到队列,而是发送到了交换机

4、每个队列都要绑定到交换机

5、生产者发送的消息,经过交换机到达队列,实现一个消息被多个消费者获取的目的

X(Exchanges):交换机一方面:接收生产者发送的消息。另一方面:知道如何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于Exchange的类型。

分类

Exchange类型有以下几种:

​ Fanout:广播,将消息交给所有绑定到交换机的队列 all

​ Direct:定向,把消息交给符合指定routing key 的队列 一堆或一个

​ Topic:通配符,把消息交给符合routing pattern(路由模式)的队列 一堆或者一个

我们这里先学习

Fanout:即广播模式

Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!

订阅模型-FANOUT

img

发布订阅模式:

在广播模式下,消息发送流程是这样的:

- 1) 可以有多个消费者

- 2) 每个消费者有自己的queue(队列)

- 3) 每个队列都要绑定到Exchange(交换机)

- 4) 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。

- 5) 交换机把消息发送给绑定过的所有队列

- 6) 队列的消费者都能拿到消息。实现一条消息被多个消费者消费

生产者

两个变化:

- 1) 声明Exchange,不再声明Queue

- 2) 发送消息到Exchange,不再发送到Queue

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.zhanglin.util.ConnectionUtil;

/**
 * 生产者
 */
public class Producter {
    //队列名称
    private static final String QUEUE = "helloword";
    //交换机
    private final static String EXCHANGE_NAME = "fanout_exchange_test";

    public static void main(String[] args) throws Exception{
        Connection connection =null;
        //通道
        Channel channel = null;
        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建与Exchange的通道,每个连接可以创建多个通道,每个通道代表一个会话任务
            channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

            //消息
            String message = "helloword!!!"+System.currentTimeMillis();
            /**
             * 消息发布方法
             * param1:Exchange的名称,如果没有指定,则使用Default Exchange
             * param2:routingKey(路由的key),消息的路由Key,是用于Exchange(交换机)将消息转发到指定的消息队列
             * param3:消息包含的属性
             * param4:消息体
             */
            /**
             * 这里没有指定交换机,消息将发送给默认交换机,每个队列也会绑定那个默认的交换机,但是不能显
             示绑定或解除绑定
             * 默认的交换机,routingKey等于队列名称
             */
            channel.basicPublish(EXCHANGE_NAME, "",null , message.getBytes());
            System.out.println("Send Message is:'" + message + "'");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}
import com.rabbitmq.client.*;
import com.zhanglin.util.ConnectionUtil;

import java.io.IOException;

/**
 * 消费者
 */
public class Consumer1 {
    //队列名称
    private final static String QUEUE_NAME = "fanout_exchange_queue_1";
    //交换机
    private final static String EXCHANGE_NAME = "fanout_exchange_test";

    public static void main(String[] args) throws Exception{
        Connection connection = null;
        Channel channel = null;

        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建通道
            channel = connection.createChannel();
            //声明队列(队列名称,是否持久化,是否独占此连接,不使用时是否自动删除此队列,队列参数)
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            //队列绑定交换机
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");
            //定义消费方法
            Channel finalChannel = channel;
            //匿名内部类
            DefaultConsumer consumer = new DefaultConsumer(finalChannel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //交换机
                    String exchange = envelope.getExchange();
                    //路由key
                    String routingKey = envelope.getRoutingKey();
                    //消息id
                    long deliveryTag = envelope.getDeliveryTag();
                    //消息内容
                    String msg = new String(body,"utf8");
                    System.out.println("receive message.." + msg);
                }
            };
            /**
             * 监听队列:QUEUE 如果有消息来了,通过consumer来处理
             * 参数明细
             * 1、队列名称
             * 2、是否自动回复,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置
             为false则需要手动回复
             * 3、消费消息的方法,消费者接收到消息后调用此方法
             */
            channel.basicConsume(QUEUE_NAME,false ,consumer );
            //阻塞住,让他一直监听
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}

订阅模型-Direct

有选择性的接收消息

在订阅模式中,生产者发布消息,所有消费者都可以获取所有消息。

在路由模式中,我们将添加一个功能 - 我们将只能订阅一部分消息。 例如,我们只能将重要的错误消息引导到日志文件(以节省磁盘空间),同时仍然能够在控制台上打印所有日志消息。

但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。

在Direct模型下,队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)

消息的发送方在向Exchange发送消息时,也必须指定消息的routing key。

img

P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。

X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列

C1:消费者,其所在队列指定了需要routing key 为 error 的消息

C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息

生产者

发送消息的RoutingKey分别是:insert、update、delete

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.zhanglin.util.ConnectionUtil;

/**
 * 生产者
 */
public class Producter {
    //队列名称
    private static final String QUEUE = "helloword";
    //交换机
    private final static String EXCHANGE_NAME = "direct_exchange_test";

    public static void main(String[] args) throws Exception{
        Connection connection =null;
        //通道
        Channel channel = null;
        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建与Exchange的通道,每个连接可以创建多个通道,每个通道代表一个会话任务
            channel = connection.createChannel();
            //声明交换-fanout广播模式
            channel.exchangeDeclare(EXCHANGE_NAME,"direct");

            //消息
            String message = "helloword!!!"+System.currentTimeMillis();
            /**
             * 消息发布方法
             * param1:Exchange的名称,如果没有指定,则使用Default Exchange
             * param2:routingKey(路由的key),消息的路由Key,是用于Exchange(交换机)将消息转发到指定的消息队列
             * param3:消息包含的属性
             * param4:消息体
             */
            /**
             * 这里没有指定交换机,消息将发送给默认交换机,每个队列也会绑定那个默认的交换机,但是不能显
             示绑定或解除绑定
             * 默认的交换机,routingKey等于队列名称
             */
            channel.basicPublish(EXCHANGE_NAME, "delete",null , message.getBytes());
            System.out.println("Send Message is:'" + message + "'");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}

消费者,绑定不同的队列

import com.rabbitmq.client.*;
import com.zhanglin.util.ConnectionUtil;

import java.io.IOException;

/**
 * 消费者
 */
public class Consumer1 {
    //队列名称
    private final static String QUEUE_NAME = "direct_exchange_queue_1";
    //交换机
    private final static String EXCHANGE_NAME = "direct_exchange_test";

    public static void main(String[] args) throws Exception{
        Connection connection = null;
        Channel channel = null;

        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建通道
            channel = connection.createChannel();
            //声明队列(队列名称,是否持久化,是否独占此连接,不使用时是否自动删除此队列,队列参数)
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            //队列绑定交换机
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"insert");
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"delete");
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"update");
            //定义消费方法
            Channel finalChannel = channel;
            //匿名内部类
            DefaultConsumer consumer = new DefaultConsumer(finalChannel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //交换机
                    String exchange = envelope.getExchange();
                    //路由key
                    String routingKey = envelope.getRoutingKey();
                    //消息id
                    long deliveryTag = envelope.getDeliveryTag();
                    //消息内容
                    String msg = new String(body,"utf8");
                    System.out.println("receive message.." + msg);
                }
            };
            /**
             * 监听队列:QUEUE 如果有消息来了,通过consumer来处理
             * 参数明细
             * 1、队列名称
             * 2、是否自动回复,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置
             为false则需要手动回复
             * 3、消费消息的方法,消费者接收到消息后调用此方法
             */
            channel.basicConsume(QUEUE_NAME,false ,consumer );
            //阻塞住,让他一直监听
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}

订阅模型-Topics

Topic类型的Exchange与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符!

Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: goods.insert

通配符规则:

​ #:匹配一个或多个词

​ *:匹配不多不少恰好1个词

举例:

​ audit.#:能够匹配audit.irs.corporate 或者 audit.irs

​ audit.*:只能匹配audit.irs

img

路由模式:

  1. 每个消费者监听自己的队列,并且设置带统配符的routingkey。
  2. 生产者将消息发给broker,由交换机根据routingkey来转发消息到指定的队列。
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.zhanglin.util.ConnectionUtil;

/**
 * 生产者
 */
public class Producter {
    //队列名称
    private static final String QUEUE = "helloword";
    //交换机
    private final static String EXCHANGE_NAME = "topic_exchange_test";

    public static void main(String[] args) throws Exception{
        Connection connection =null;
        //通道
        Channel channel = null;
        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建与Exchange的通道,每个连接可以创建多个通道,每个通道代表一个会话任务
            channel = connection.createChannel();
            //声明交换-topic模式
            channel.exchangeDeclare(EXCHANGE_NAME,"topic",false);
            //消息
            String message = "helloword!!!"+System.currentTimeMillis();
            /**
             * 消息发布方法
             * param1:Exchange的名称,如果没有指定,则使用Default Exchange
             * param2:routingKey(路由的key),消息的路由Key,是用于Exchange(交换机)将消息转发到指定的消息队列
             * param3:消息包含的属性
             * param4:消息体
             */
            /**
             * 这里没有指定交换机,消息将发送给默认交换机,每个队列也会绑定那个默认的交换机,但是不能显
             示绑定或解除绑定
             * 默认的交换机,routingKey等于队列名称
             */
            channel.basicPublish(EXCHANGE_NAME, "delete",null , message.getBytes());
            System.out.println("Send Message is:'" + message + "'");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}
import com.rabbitmq.client.*;
import com.zhanglin.util.ConnectionUtil;

import java.io.IOException;

/**
 * 消费者
 */
public class Consumer1 {
    //队列名称
    private final static String QUEUE_NAME = "direct_exchange_queue_1";
    //交换机
    private final static String EXCHANGE_NAME = "topic_exchange_test";

    public static void main(String[] args) throws Exception{
        Connection connection = null;
        Channel channel = null;

        try {
            //获取连接
            connection = ConnectionUtil.getConnection();
            //创建通道
            channel = connection.createChannel();
            //声明队列(队列名称,是否持久化,是否独占此连接,不使用时是否自动删除此队列,队列参数)
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            //队列绑定交换机
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"item.insert");
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"item.delete");
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"item.update");
            //定义消费方法
            Channel finalChannel = channel;
            //匿名内部类
            DefaultConsumer consumer = new DefaultConsumer(finalChannel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //交换机
                    String exchange = envelope.getExchange();
                    //路由key
                    String routingKey = envelope.getRoutingKey();
                    //消息id
                    long deliveryTag = envelope.getDeliveryTag();
                    //消息内容
                    String msg = new String(body,"utf8");
                    System.out.println("receive message.." + msg);
                }
            };
            /**
             * 监听队列:QUEUE 如果有消息来了,通过consumer来处理
             * 参数明细
             * 1、队列名称
             * 2、是否自动回复,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置
             为false则需要手动回复
             * 3、消费消息的方法,消费者接收到消息后调用此方法
             */
            channel.basicConsume(QUEUE_NAME,false ,consumer );
            //阻塞住,让他一直监听
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}

Springboot整合rabbitmq

搭建boot环境

使用spring-boot-starter-amqp会自动添加spring-rabbit依赖

pom

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <!--spirngboot集成rabbitmq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
    </dependencies>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.0.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

配置application.yml

server:
  port: 44000
spring:
  application:
    name: test‐rabbitmq‐producer
rabbitmq:
  host: 127.0.0.1
  port: 5672
  username: guest
  password: guest
  virtualHost: /

入口类

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }
}

配置类

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitmqConfig {
    public static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    public static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    public static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";

    /**
     * 交换机配置
     * ExchangeBuilder提供了fanout、direct、topic、header交换机类型的配置
     *
     * @return the exchange
     */
    @Bean(EXCHANGE_TOPICS_INFORM)
    public Exchange EXCHANGE_TOPICS_INFORM() {
    //durable(true)持久化,消息队列重启后交换机仍然存在
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build();
    }

    //声明队列
    @Bean(QUEUE_INFORM_SMS)
    public Queue QUEUE_INFORM_SMS() {
        Queue queue = new Queue(QUEUE_INFORM_SMS);
        return queue;
    }

    //声明队列
    @Bean(QUEUE_INFORM_EMAIL)
    public Queue QUEUE_INFORM_EMAIL() {
        Queue queue = new Queue(QUEUE_INFORM_EMAIL);
        return queue;
    }

    /**
     * channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
     * 绑定队列到交换机 .
     *
     * @param queue    the queue
     * @param exchange the exchange
     * @return the binding
     */
    @Bean
    public Binding BINDING_QUEUE_INFORM_SMS(@Qualifier(QUEUE_INFORM_SMS) Queue queue,
                                            @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("inform.#.sms.#").noargs();
    }

    @Bean
    public Binding BINDING_QUEUE_INFORM_EMAIL(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue,
                                              @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("inform.#.email.#").noargs();
    }
}

生产者

使用RarbbitTemplate发送消息

import cn.itsource.config.RabbitmqConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = App.class)
@RunWith(SpringRunner.class)
public class Producer05_topics_springboot {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Test
    public void testSendByTopics() {
        for (int i = 0; i < 5; i++) {
            String message = "sms email inform to user" + i;
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS_INFORM, "inform.sms.email", message);
            System.out.println("Send Message is:'" + message + "'");
        }
    }
}

消费端

import cn.itsource.config.RabbitmqConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ReceiveHandler {
    //监听email队列
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_EMAIL})
    public void receive_email(String msg, Message message, Channel channel) {
        System.out.println(msg);
    }

    //监听sms队列
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_SMS})
    public void receive_sms(String msg, Message message, Channel channel) {
        System.out.println(msg);
    }
}

页面静态化

课程主页的访问人数非常多, 以不发请求静态页面代替要发请求静态页面或者动态页面.没有对后台数据获取.

课程详情页:只要课程信息不改,详情页就不会改变.

官网主页:一定的时间段是不可变

招聘主页:一定的时间段是不可变

职位详情:只要职位信息不改,详情页就不会改变.

有的页面访问人数很多,但是在一定时间段内不会改变.页面静态化.

静态化好处

①降低数据库或缓存压力

②提高响应速度,增强用户体验.

基本分析

静态页面=模板技术+数据

静态页面生成时机:

​ ①当部署并启动,需要在后台管理里面触发一个按钮,初始化静态页面. 初始化

​ ②当数据(类型,广告等)发生改变后,要覆盖原来静态页面. 替换

方案:页面静态化,通过模板技术来实现.

.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ReceiveHandler {
//监听email队列
@RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_EMAIL})
public void receive_email(String msg, Message message, Channel channel) {
System.out.println(msg);
}

//监听sms队列
@RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_SMS})
public void receive_sms(String msg, Message message, Channel channel) {
    System.out.println(msg);
}

}


页面静态化 
课程主页的访问人数非常多, 以不发请求静态页面代替要发请求静态页面或者动态页面.没有对后台数据获取.

课程详情页:只要课程信息不改,详情页就不会改变.

官网主页:一定的时间段是不可变

招聘主页:一定的时间段是不可变

职位详情:只要职位信息不改,详情页就不会改变.

有的页面访问人数很多,但是在一定时间段内不会改变.页面静态化.

静态化好处

  ①降低数据库或缓存压力

  ②提高响应速度,增强用户体验.

基本分析

 静态页面=模板技术+数据

 静态页面生成时机:

​    ①当部署并启动,需要在后台管理里面触发一个按钮,初始化静态页面. 初始化

​    ②当数据(类型,广告等)发生改变后,要覆盖原来静态页面.  替换

 方案:页面静态化,通过模板技术来实现.

模板技术:freemaker,velocity,thymeleaf等
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值