IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringBoot+ActiveMQ实现订单在N秒后未付款就自动取消此订单 -> 正文阅读

[Java知识库]SpringBoot+ActiveMQ实现订单在N秒后未付款就自动取消此订单

一、大佬给的配置

spring:
  #activemq延迟队列
  activemq:
    inMemory: false
    broker-url: tcp://47.108.204.1:61616
    user: admin
    password: admin

二、添加依赖和俩文件

在这里插入图片描述

ActiveMQ依赖

<!--activeMq-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

第一个配置文件------ActiveMQConfiguration

package com.nxt.order.utils.ActiveMQ;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;

/**
 * @author LunarYouI
 * @create 2021-08-04 11:34
 */
@Configuration
public class ActiveMQConfiguration {

    //这个Bean用于和mq建立连接、mq的地址、用户名、密码从配置文件中获取
    @Bean(name = "innerConnectionFactory")
    @Primary
    public ActiveMQConnectionFactory firstConnectionFactory(
            //mq服务地址
            @Value("${spring.activemq.broker-url}") String brokerUrl,
            //mq用户名
            @Value("${spring.activemq.user}") String username,
            //mq密码
            @Value("${spring.activemq.password}") String password) {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
        factory.setBrokerURL(brokerUrl);
        factory.setUserName(username);
        factory.setPassword(password);
        factory.setTrustAllPackages(true);
        factory.setMaxThreadPoolSize(ActiveMQConnection.DEFAULT_THREAD_POOL_SIZE);
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        //定义ReDelivery(重发机制)机制 ,重发时间间隔是100毫秒,最大重发次数是3次
        //是否在每次尝试重新发送失败后,增长这个等待时间
        redeliveryPolicy.setUseExponentialBackOff(true);
        //重发次数,默认为6次   这里设置为1次
        redeliveryPolicy.setMaximumRedeliveries(1);
        //重发时间间隔,默认为1秒
        redeliveryPolicy.setInitialRedeliveryDelay(1000);
        //第一次失败后重新发送之前等待500毫秒,第二次失败再等待500 * 2毫秒,这里的2就是value
        redeliveryPolicy.setBackOffMultiplier(2);
        //最大传送延迟,只在useExponentialBackOff为true时有效(V5.5),假设首次重连间隔为10ms,倍数为2,那么第
        //二次重连时间间隔为 20ms,第三次重连时间间隔为40ms,当重连时间间隔大的最大重连时间间隔时,以后每次重连时间间隔都为最大重连时间间隔。
        redeliveryPolicy.setMaximumRedeliveryDelay(1000);
        factory.setRedeliveryPolicy(redeliveryPolicy);
        return factory;
    }

    //在Topic模式中,对消息的监听需要对containerFactory进行配置
    @Bean("topicJmsListenerContainerFactory")
    public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(
            //将“innerConnectionFactory”这个Bean注入
            @Qualifier("innerConnectionFactory") ActiveMQConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setSessionTransacted(true);
        factory.setPubSubDomain(true);
        return factory;
    }

    // 在Queue模式中,对消息的监听需要对containerFactory进行配置
    @Bean("queueJmsListenerContainerFactory")
    public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(
            //将“innerConnectionFactory”这个Bean注入
            @Qualifier("innerConnectionFactory") ActiveMQConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setSessionTransacted(true);
        factory.setPubSubDomain(false);
        return factory;
    }
}

第二个配置文件------ActivemqOperator

package com.nxt.order.utils.ActiveMQ;

import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.jms.*;

/**
 * @author LunarYouI
 * @create 2021-08-04 11:36
 */
@Component
public class ActivemqOperator {
    private final JmsMessagingTemplate jmsTemplate;
    @Autowired
    public ActivemqOperator(JmsMessagingTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * 发送主题消息
     */
    public void sendMsgTopic(String topic, String message) {
        Destination destination = new ActiveMQTopic(topic);
        jmsTemplate.convertAndSend(destination, message);
    }

    /**
     * 发送队列消息
     */
    public void sendMsgQueue(String queue, String message) {
        Destination destination = new ActiveMQQueue(queue);
        jmsTemplate.convertAndSend(destination, message);
    }

    /**
     * 发送延时队列消息
     */
    public <T> void delaySend(String queue, String message, Long time) {
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
        Destination destination = new ActiveMQQueue(queue);
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(destination);
            producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
            ObjectMessage objectMessage = session.createObjectMessage(message);

            objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);

            producer.send(objectMessage);
            session.commit();
        } catch (Exception e) {
            throw new RuntimeException("delaySend exception : " + e.getMessage());
        } finally {
            try {
                if (producer != null) {
                    producer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

三、演示效果

package com.nxt.order.controller;

import com.nxt.order.utils.ActiveMQ.ActivemqOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author LunarYouI
 * @create 2021-08-04 11:42
 */
@RequestMapping("/testMq")
@RestController
public class Testaaaaa {
    @Autowired
    ActivemqOperator activemqOperator;

    @GetMapping("/queue")
    public String testMqQueue() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("当前订单【123456789】生成时间: "+df.format(new Date()));// new Date()为获取当前系统时间
        //设置延时时间推送到activeMQ
        activemqOperator.delaySend("testQueue","延时10S",10000L);
        return "OK";
    }

    @JmsListener(destination = "testQueue", containerFactory = "queueJmsListenerContainerFactory")
    public void listenerMq(String message) {
        //业务逻辑,根据单号查询是否已经付款
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("当前订单【123456789】失效时间: " + df.format(new Date()));// new Date()为获取当前系统时间
    }
}

在这里插入图片描述
如果我们把生成时间改成订单创建,失效时间改成订单结束时间到了 订单失效,那么此功能就算实现了

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-08-05 17:11:57  更:2021-08-05 17:15:58 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/12 1:13:31-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码