Why this article? Because the company wanted to time push messages from live rooms, it came up with the idea of using MQ’s delayed queue to time push messages. Well, to experiment with the standalone version, the previous article set up MQ and enabled setting up addresses for delayed task support

Set up producer

If we are using Tencent cloud live, then we have introduced the relevant JAR package (find it yourself) POM.xml

<! -- activemq --> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-spring</artifactId> <version>${activemq-pool.version}</version> </dependency> <! -- spring-jms --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring.version}</version>
		</dependency>
Copy the code
  • Introduce support for MQ

Assuming that there is no outage and you use Activemq’s point-to-point mode then modify the XML (yes, SSM again, Spring MVC)

  • Creating a connection Factory
<! -- CachingConnectionFactory Connection factory --> <bean id="cachingConnectionFactory"
        class="org.springframework.jms.connection.CachingConnectionFactory"> <! -- Session cache number --> <property name="sessionCacheSize" value="20" />
        <property name="targetConnectionFactory">  
            <bean class="org.apache.activemq.ActiveMQConnectionFactory"> <! -- MQ address account name password --> <property name="brokerURL" value="TCP: / / 192.168.1.195:61616? wireFormat.maxInactivityDuration=0" />
                <property name="userName" value="admin" />
                <property name="password" value="admin"/ > <! -- Send asynchronously --> <property name="useAsyncSend" value="true"/>
                <property name="trustAllPackages" value="true"/>
            </bean>  
        </property>  
    </bean>
Copy the code
  • Create a queue
<! -- Define message Queue name --> <bean id="liveQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"> <! <constructor-arg> <value>liveMQQueue</value> </constructor-arg> </bean>Copy the code
  • Configuring the JMS Template
<! -- Configure JMS templates (Queue), JMS utility classes provided by Spring, which send and receive messages. --> <bean id="liveJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
             <property name="connectionFactory" ref="cachingConnectionFactory" />
           <property name="defaultDestination" ref="liveQueueDestination" />
            <property name="receiveTimeout" value="10000"/ > <! --trueIs the topic,falseIt's queue. The default is queuefalse, displays writefalse -->
            <property name="pubSubDomain" value="false" />
        </bean>

Copy the code
  • Create producer code
@Component
public class LiveJmsProducer {
    @Resource(name = "liveJmsTemplate") private JmsTemplate liveJmsTemplate; Public void sendMessageAndTime(final String MSG,Long timel) {public void sendMessageAndTime(final String MSG,Long timel) {  long delayTime = timel * 60000; try { liveJmsTemplate.send(newMessageCreator() {
                public Message createMessage(Session session) throws JMSException {
                    TextMessage message = session.createTextMessage(msg);
                    message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delayTime);
                    returnmessage; }}); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

The delay time is in minutes, which seems reasonable

Create consumers

  • The XML configuration
 <bean id="liveQueueReceiver"
          class="com.backend.service.jms.JmsLiveConsumer"></bean>
    <jms:listener-container destination-type="queue"
                            container-type="default" connection-factory="cachingConnectionFactory"
                            acknowledge="auto">
        <jms:listener destination="liveMQQueue" ref="liveQueueReceiver" />
    </jms:listener-container>
Copy the code
  • Consumer code
@Component
public class JmsLiveConsumer implements MessageListener {
	
	protected final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private TencentIMService tencentIMService;
	@Autowired
	private LiveSystemMsgMapper liveSystemMsgMapper;
	
	@Override
	public void onMessage(Message message) {
		TextMessage tm = (TextMessage) message;
		try {
            LiveSystemMsgEntity liveSystemMsgEntity = JSONObject.parseObject(tm.getText(),LiveSystemMsgEntity.class);
			String sendName = "System Administrator" ;
			LiveSystemMsgEntity liveSystemMsgCheck = liveSystemMsgMapper.selectById(liveSystemMsgEntity.getId());
			if (liveSystemMsgCheck == null) {
				return;
			}
			if(liveSystemMsgCheck.getSendName()! =null&& liveSystemMsgCheck.getSendName() ! ="") { sendName = liveSystemMsgCheck.getSendName(); } // Determine whether the message can be pushedif (liveSystemMsgCheck.getStatus()==3){
					return; } Element elementElem = new Element(); elementElem.setText(liveSystemMsgEntity.getMsgContentText()); TIMMsgElement timMsgElementElem = new TIMMsgElement(); timMsgElementElem.setMsgContent(elementElem); timMsgElementElem.setMsgType("TIMCustomElem"); Element elementText = new Element(); elementText.setText(liveSystemMsgEntity.getMsgContentText()); TIMMsgElement timMsgElementText = new TIMMsgElement(); timMsgElementText.setMsgContent(elementText); timMsgElementText.setMsgType("TIMTextElem");
            List<TIMMsgElement> list = new ArrayList<TIMMsgElement>();
            list.add(timMsgElementElem);
            list.add(timMsgElementText);

			SendGroupMsgResponse sendGroupMsgResponse = tencentIMService.sendSystemGroupMsg(list,liveSystemMsgEntity.getGroupId());
            if (!"OK".equals(sendGroupMsgResponse.getActionStatus())) {
                logger.error("Failed to send remote message :"+sendGroupMsgResponse.toString());
            }
		} catch (JMSException e) {
		    logger.warn("Failed to receive delayed message"+e); }}}Copy the code

TencentIMService will not be given to you, just wrap a layer of Tencent Cloud IM API OK and start sending messages

Logging In to the MQ Background

Default password Account admin

Ok, success, oh yeah