当前位置:   article > 正文

RabbitMQ之SSM框架整合xml配置

rabbitmq简单的队列推送xml配置

      前提:jdk1.8,本博客使用的是RabbitTemplate模版,用封装好的方法,不再使用 ==》入门级教学

      还有一个重点,自己一定要会使用rabbitmq服务器,自己创建exchange、queue等,不然使用该博客的话,会报错的。

      两种方法:topic模式以及延迟队列的使用

1、pom
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.5.16</version>
</dependency>

<dependency>
    <groupId>org.springframework.amqp</groupId>
    <artifactId>spring-rabbit</artifactId>
    <version>1.7.11.RELEASE</version>
</dependency>
2、application.properties
# rabbitmq 消息配置
rabbitmq.addresses=localhost:5672
rabbitmq.virtual-host=/
rabbitmq.username=guest
rabbitmq.password=guest
rabbitmq.channel-cache-size=50
rabbitmq.concurrentConsumers=3
rabbitmq.maxConcurrentConsumers=10
# 确认方式 MANUAL 手动,AUTO 自动,NONE 自动确认
rabbitmq.acknowledgeMode=MANUAL
# 线程池数量 = 并发数 * 监听数
rabbitmq.task-executor.pool-size=100
3、spring-rabbit.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/rabbit
   http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
   http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <!--启用注解监听消息-->
    <rabbit:annotation-driven/>

    <!-- 配置连接工厂 -->
    <rabbit:connection-factory id="connectionFactory"
                               host="localhost"
                               port="5672"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}" />

    <!-- 定义mq管理 -->
    <rabbit:admin connection-factory="connectionFactory" />

    <!-- 声明队列 -->
    <rabbit:queue name="topicqueue2" auto-declare="false" durable="true"></rabbit:queue>
    <rabbit:queue name="queue_seckill" auto-declare="false" durable="true"></rabbit:queue>
    <rabbit:queue name="dlx_delay_queue" auto-declare="false" durable="true">
        <rabbit:queue-arguments>
            <entry key="x-message-ttl" value="6000" value-type="java.lang.Long"/>
            <entry key="x-dead-letter-exchange" value="dlx_delay_exchange" />
            <entry key="x-dead-letter-routing-key" value="immediate_road" />
        </rabbit:queue-arguments>
    </rabbit:queue>
    <rabbit:queue name="immediate" auto-declare="false" durable="true">
    </rabbit:queue>
    <!--producer-->

    <!-- 定义交换机绑定队列(通配符模式) #匹配一个或多个词  *匹配一个词 -->
    <rabbit:topic-exchange name="IExchange" id="IExchange">
        <rabbit:bindings>
            <rabbit:binding queue="topicqueue2" pattern="lazy.#"/>
            <rabbit:binding queue="queue_seckill" pattern="seckill.#"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

    <!--延迟队列-->
    <rabbit:direct-exchange name="dlx_delay_exchange" durable="true" auto-declare="false">
        <rabbit:bindings>
            <rabbit:binding queue="dlx_delay_queue" key="dlx_delay_road" />
            <rabbit:binding queue="immediate" key="immediate_road" />
        </rabbit:bindings>
    </rabbit:direct-exchange>

    <!-- 消息对象json转换类 -->
    <bean id="jsonMessageConverter"
          class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />

    <!-- 定义模版 -->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter" />


    <!-- 定义消费者 -->
    <bean name="delayConsumer" class="com.platform.mq.DelayListener" />
    <bean name="seckillConsumer" class="com.platform.mq.SeckillHandler" />

    <!-- 定义消费者监听队列 -->
    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener ref="seckillConsumer" queues="queue_seckill" />
        <rabbit:listener ref="delayConsumer" queues="immediate" />
    </rabbit:listener-container>

    <!--消息监听容器,配合注解监听消息-->
    <bean id="rabbitListenerContainerFactory" class="org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--并发消费者数量-->
        <property name="concurrentConsumers" value="${rabbitmq.concurrentConsumers:3}"/>
        <!--最大数量-->
        <property name="maxConcurrentConsumers" value="${rabbitmq.maxConcurrentConsumers:10}"/>
        <!--消息转换-->
        <property name="messageConverter" ref="jsonMessageConverter"/>
        <!--任务线程池-->
        <property name="taskExecutor">
            <task:executor id="amqpTaskExecutor" pool-size="${rabbitmq.task-executor.pool-size:100}"/>
        </property>
        <!--手动确认-->
        <property name="acknowledgeMode" value="MANUAL"/>
    </bean>
</beans>
4、监听器
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

/**
 * @Author:MuJiuTian
 * @Description: RabbitMq延迟队列 https://blog.csdn.net/m912595719/article/details/83787486
 * ChannelAwareMessageListener(Message memssage,Channel channel) MessageListener(Message message)
 * @Date: Created in 下午4:17 2019/8/12
 */

public class DelayListener implements MessageListener {

    @Autowired
    RabbitTemplate rabbitTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void onMessage(Message message) {
        try {
            JsonNode jsonData = MAPPER.readTree(message.getBody());
            System.out.println("延迟队列时间为:"+DateUtil.format(new Date(), DateFormat.getDateTimeInstance()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.service.SeckillService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author:MuJiuTian
 * @Description: 秒杀消费者消费消息,监听执行业务逻辑处理
 * @Date: Created in 下午5:01 2019/8/14
 */
public class SeckillHandler implements MessageListener {

    @Autowired
    SeckillService seckillService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void onMessage(Message message) {
        try {
            //队列中继续执行秒杀
            JsonNode jsonData = MAPPER.readTree(message.getBody());
            String goodsId = jsonData.get("goodsId").asText();
            int productId = jsonData.get("productId").asInt();
            int userId    = jsonData.get("userId").asInt();
            int sellerNum = jsonData.get("sellerNum").asInt();
            //开始秒杀
            seckillService.seckillRedis(goodsId,productId,sellerNum,userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
5、实体类
public class Mail implements Serializable {
    private static final long serialVersionUID = -8140693840257585779L;
    private String mailId;
    private String country;
    private Double weight;


    public Mail() {
    }

    public Mail(String mailId, String country, double weight) {
        this.mailId = mailId;
        this.country = country;
        this.weight = weight;
    }

    public String getMailId() {
        return mailId;
    }

    public void setMailId(String mailId) {
        this.mailId = mailId;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Mail [mailId=" + mailId + ", country=" + country + ", weight="
                + weight + "]";
    }
}
6、controller
/**
 * topic:通配符模式
 */
@GetMapping(value = "/test7")
public void test11(){
    Mail mail = new Mail("21","China",27.2);
    System.out.println("topic模式发送数据到消息队列"+DateUtil.format(new Date(), DateFormat.getDateTimeInstance()));
    rabbitTemplate.convertAndSend("IExchange","lazy.dtb",mail);
}



/**
 * 死信队列 long等待时间,目前测试为:自动消费
 */
@GetMapping(value = "/test8")
public void test13(long time) throws IOException {
    Mail mail = randomMail();
    System.out.println("延迟队列:dlx方式"+DateUtil.format(new Date(), DateFormat.getDateTimeInstance()));
    rabbitTemplate.convertAndSend("dlx_delay_exchange","dlx_delay_road", mail, message -> {
        message.getMessageProperties().setExpiration(time + "");
        return message;
    });
}


/**
 * 随机创建一个Mail实体对象,供接口测试
 */
public static Mail randomMail() {
    Mail mail = new Mail();
    mail.setMailId(new Random().nextInt(100)+"");
    mail.setCountry("China");
    mail.setWeight(new Random().nextDouble());
    return mail;
}

      ok!

转载于:https://my.oschina.net/mdxlcj/blog/3096142

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/139237?site
推荐阅读
相关标签
  

闽ICP备14008679号