实战05_SSM整合ActiveMQ支持多种类型消息

ActiveMQ 专栏收录该内容
16 篇文章 0 订阅

接上一篇:实战04_SSM整合ActiveMQ支持多种类型消息https://blog.csdn.net/weixin_40816738/article/details/100572124

1、StreamMessage java原始值数据流
2、MapMessage 键值对
3、TextMessage 字符串
4、ObjectMessage 一个序列化的java对象
5、BytesMessage 一个字节的数据流

此文章为企业实战的展示操作,如果有地方不懂请留言,我看到后,会进行统一回复,让我们一起进步,为自己加油!!!

项目名项目说明
ssm-activemq父工程,统一版本控制
producer生产者
consumer消费者
base-pojo公共实体类
base-dao公共接口,数据库连接

五、生产者producer

5.1. 创建QueueController

package com.gblfy.mq.controller;

import com.alibaba.fastjson.JSON;
import com.gblfy.mq.entity.User;
import com.gblfy.mq.service.IQueueProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jms.Destination;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gblfy
 * @ClassNme QueueController
 * @Description TODO
 * @Date 2019/8/31 18:45
 * @version1.0
 */
@Controller
@RequestMapping("/queue")
public class QueueController {

    @Autowired
    private Destination QUEUE_Str;//传递Str字符串
    @Autowired
    private Destination QUEUE_Str_LIST;//传递传递JSON字符串
    @Autowired
    private Destination QUEUE_OBJ;//传递OBJ对象
    @Autowired
    private Destination QUEUE_MAP;//传递MAP

    @Autowired
    private IQueueProductService iQueueProductService;

    /**
     * 发送消息类型 String
     * 测试链接:http://localhost:8080/queue/itemList
     *
     * @return
     */
    @RequestMapping("/str")
    @ResponseBody
    public String sendStringMessage() {
        String messge = "send string type message";
        iQueueProductService.sendStringMessage(QUEUE_Str, messge);
        return "success";
    }

    /**
     * 发送消息类型 List
     * <p>
     * 1.List<User>转成jsonString
     * 2.由于list没有实现序列化,因此不能传递对象
     * <p>
     * 测试链接:http://localhost:8080/queue/objList
     *
     * @return
     */
    @RequestMapping("/objList")
    @ResponseBody
    public String sendListMessage() {
        //获取对象
        User user = getObj();
        //将获取对象芳容List
        List<User> userList = getListObj(user);
        //把对象列表转成jsonString
        String jsonString = JSON.toJSONString(userList);
        iQueueProductService.sendListMessage(QUEUE_Str_LIST, jsonString);
        return "success";
    }

    /**
     * 发送消息类型 Obj
     * <p>
     * 测试链接:http://localhost:8080/queue/obj
     *
     * @return
     */
    @RequestMapping("/obj")
    @ResponseBody
    public String sendObjMessage() {
        //获取对象
        User user = getObj();
        //把对象传递
        iQueueProductService.sendObjMessage(QUEUE_OBJ, user);
        return "success";
    }

    /**
     * 发送消息类型 MAP
     * <p>
     * 测试链接:http://localhost:8080/queue/map
     *
     * @return
     */
    @RequestMapping("/map")
    @ResponseBody
    public String sendMapMessage() {
        String mapKey = "mapKey";
        String mapValue = "mapValue";
        //把map传递
        iQueueProductService.sendMapMessage(QUEUE_MAP, mapKey, mapValue);
        return "success";
    }

    /**
     * 封装map
     *
     * @param key
     * @param object
     * @return
     */
    public Map<String, Object> getMap(String key, Object object) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, object);
        return map;
    }

    /**
     * 封装List
     *
     * @param user
     * @return
     */
    public List<User> getListObj(User user) {
        List<User> userList = new ArrayList<User>();
        userList.add(user);
        return userList;
    }

    /**
     * 封装公用对象
     *
     * @return
     */
    private User getObj() {
        //封装测试数据
        User user = new User().builder()
                .id("1")
                .name("yuxin")
                .age(02)
                .build();
        return user;
    }
}

5.2. 创建QueueController

package com.gblfy.mq.controller;

import com.alibaba.fastjson.JSON;
import com.gblfy.mq.entity.User;
import com.gblfy.mq.service.ITopicProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jms.Destination;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gblfy
 * @ClassNme TOPICController
 * @Description TODO
 * @Date 2019/8/31 18:45
 * @version1.0
 */
@Controller
@RequestMapping("/topic")
public class TopicController {

    @Autowired
    private Destination TOPIC_Str;//传递Str字符串
    @Autowired
    private Destination TOPIC_Str_LIST;//传递传递JSON字符串
    @Autowired
    private Destination TOPIC_OBJ;//传递OBJ对象
    @Autowired
    private Destination TOPIC_MAP;//传递MAP

    @Autowired
    private ITopicProductService iTopicProductService;

    /**
     * 发送消息类型 String
     * 测试链接:http://localhost:8080/topic/itemList
     *
     * @return
     */
    @RequestMapping("/str")
    @ResponseBody
    public String sendStringMessage() {
        String messge = "send string type message";
        iTopicProductService.sendStringMessage(TOPIC_Str, messge);
        return "success";
    }

    /**
     * 发送消息类型 List
     * <p>
     * 1.List<User>转成jsonString
     * 2.由于list没有实现序列化,因此不能传递对象
     * <p>
     * 测试链接:http://localhost:8080/topic/objList
     *
     * @return
     */
    @RequestMapping("/objList")
    @ResponseBody
    public String sendListMessage() {
        //获取对象
        User user = getObj();
        //将获取对象芳容List
        List<User> userList = getListObj(user);
        //把对象列表转成jsonString
        String jsonString = JSON.toJSONString(userList);
        iTopicProductService.sendListMessage(TOPIC_Str_LIST, jsonString);
        return "success";
    }

    /**
     * 发送消息类型 Obj
     * <p>
     * 测试链接:http://localhost:8080/topic/obj
     *
     * @return
     */
    @RequestMapping("/obj")
    @ResponseBody
    public String sendObjMessage() {
        //获取对象
        User user = getObj();
        //把对象传递
        iTopicProductService.sendObjMessage(TOPIC_OBJ, user);
        return "success";
    }

    /**
     * 发送消息类型 MAP
     * <p>
     * 测试链接:http://localhost:8080/topic/map
     *
     * @return
     */
    @RequestMapping("/map")
    @ResponseBody
    public String sendMapMessage() {
        String mapKey = "mapKey";
        String mapValue = "mapValue";
        //把map传递
        iTopicProductService.sendMapMessage(TOPIC_MAP, mapKey, mapValue);
        return "success";
    }

    /**
     * 封装map
     *
     * @param key
     * @param object
     * @return
     */
    public Map<String, Object> getMap(String key, Object object) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, object);
        return map;
    }

    /**
     * 封装List
     *
     * @param user
     * @return
     */
    public List<User> getListObj(User user) {
        List<User> userList = new ArrayList<User>();
        userList.add(user);
        return userList;
    }

    /**
     * 封装公用对象
     *
     * @return
     */
    private User getObj() {
        //封装测试数据
        User user = new User().builder()
                .id("1")
                .name("yuxin")
                .age(02)
                .build();
        return user;
    }
}

5.3. 创建IQueueProductService接口

package com.gblfy.mq.service;

import javax.jms.Destination;
import java.io.Serializable;

public interface IQueueProductService {

    /**
     * 发送消息类型  String
     *
     * @param destination
     * @param msg
     */
    void sendStringMessage(Destination destination, final String msg);

    /**
     * 送消息类型 List
     *
     * @param destination
     * @param msg
     */
    void sendListMessage(Destination destination, final String msg);

    /**
     * 发送消息类型 Obj
     *
     * @param destination
     * @param obj
     */
    void sendObjMessage(Destination destination, final Serializable obj);

    /**
     * 发送消息类型 map
     *
     * @param destination
     * @param message
     */
    void sendMapMessage(Destination destination, final String mapKey, final String message);

    /**
     * 向指定Destination发送字节消息
     *
     * @param destination
     * @param bytes
     */
    void sendBytesMessage(Destination destination, final byte[] bytes);

    /**
     * 向默认队列发送Stream消息
     */
    void sendStreamMessage(Destination destination);
}

5.4. 创建ITopicProductService接口

package com.gblfy.mq.service;

import javax.jms.Destination;
import java.io.Serializable;

public interface ITopicProductService {

    /**
     * 发送消息类型  String
     *
     * @param destination
     * @param msg
     */
    void sendStringMessage(Destination destination, final String msg);

    /**
     * 送消息类型 List
     *
     * @param destination
     * @param msg
     */
    void sendListMessage(Destination destination, final String msg);

    /**
     * 发送消息类型 Obj
     *
     * @param destination
     * @param obj
     */
    void sendObjMessage(Destination destination, final Serializable obj);

    /**
     * 发送消息类型 map
     *
     * @param destination
     * @param message
     */
    void sendMapMessage(Destination destination, final String mapKey, final String message);

    /**
     * 向指定Destination发送字节消息
     *
     * @param destination
     * @param bytes
     */
    void sendBytesMessage(Destination destination, final byte[] bytes);

    /**
     * 向默认队列发送Stream消息
     */
    void sendStreamMessage(Destination destination);
}

5.5. 创建QueueProductServiceImpl实现类

package com.gblfy.mq.service.impl;

import com.gblfy.mq.service.IQueueProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.io.Serializable;

/**
 * @author gblfy
 * @ClassNme QueueProductService
 * @Description TODO
 * @Date 2019/9/4 14:43
 * @version1.0
 */
@Service
public class QueueProductServiceImpl implements IQueueProductService {

    @Autowired
    private JmsTemplate jmsQueueTemplate;

    /**
     * 发送消息类型  String
     *
     * @param destination
     * @param msg
     */
    public void sendStringMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 送消息类型 List
     *
     * @param destination
     * @param msg
     */
    public void sendListMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 发送消息类型 Obj
     *
     * @param destination
     * @param obj
     */
    public void sendObjMessage(Destination destination, final Serializable obj) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(obj);
            }
        });
    }

    /**
     * 发送消息类型 map
     *
     * @param destination
     * @param message
     */
    public void sendMapMessage(Destination destination, final String mapKey, final String message) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString(mapKey, message);
                return mapMessage;
            }
        });
        System.out.println("springJMS send map message...");
    }

    /**
     * 向指定Destination发送字节消息
     *
     * @param destination
     * @param bytes
     */
    public void sendBytesMessage(Destination destination, final byte[] bytes) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(bytes);
                return bytesMessage;

            }
        });
        System.out.println("springJMS send bytes message...");
    }

    /**
     * 向默认队列发送Stream消息
     */
    public void sendStreamMessage(Destination destination) {
        jmsQueueTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                StreamMessage message = session.createStreamMessage();
                message.writeString("stream string");
                message.writeInt(11111);
                return message;
            }
        });
        System.out.println("springJMS send Strem message...");
    }
}

5.6. 创建TopicProductServiceImpl实现类

package com.gblfy.mq.service.impl;

import com.gblfy.mq.service.ITopicProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.io.Serializable;

/**
 * @author gblfy
 * @ClassNme QueueProductService
 * @Description TODO
 * @Date 2019/9/4 14:43
 * @version1.0
 */

@Service
public class TopicProductServiceImpl implements ITopicProductService {

    @Autowired
    private JmsTemplate jmsTopicTemplate;

    /**
     * 发送消息类型  String
     *
     * @param destination
     * @param msg
     */
    public void sendStringMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsTopicTemplate.getDefaultDestination();
        }
        jmsTopicTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 送消息类型 List
     *
     * @param destination
     * @param msg
     */
    public void sendListMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsTopicTemplate.getDefaultDestination();
        }
        jmsTopicTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 发送消息类型 Obj
     *
     * @param destination
     * @param obj
     */
    public void sendObjMessage(Destination destination, final Serializable obj) {
        if (null == destination) {
            destination = jmsTopicTemplate.getDefaultDestination();
        }
        jmsTopicTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(obj);
            }
        });
    }

    /**
     * 发送消息类型 map
     *
     * @param destination
     * @param message
     */
    public void sendMapMessage(Destination destination, final String mapKey, final String message) {
        if (null == destination) {
            destination = jmsTopicTemplate.getDefaultDestination();
        }
        jmsTopicTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString(mapKey, message);
                return mapMessage;
            }
        });
        System.out.println("springJMS send map message...");
    }

    /**
     * 向指定Destination发送字节消息
     *
     * @param destination
     * @param bytes
     */
    public void sendBytesMessage(Destination destination, final byte[] bytes) {
        if (null == destination) {
            destination = jmsTopicTemplate.getDefaultDestination();
        }
        jmsTopicTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(bytes);
                return bytesMessage;

            }
        });
        System.out.println("springJMS send bytes message...");
    }

    /**
     * 向默认队列发送Stream消息
     */
    public void sendStreamMessage(Destination destination) {
        jmsTopicTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                StreamMessage message = session.createStreamMessage();
                message.writeString("stream string");
                message.writeInt(11111);
                return message;
            }
        });
        System.out.println("springJMS send Strem message...");
    }
}

5.7. 在resources 目录下创建spring文件夹

5.7.1. 在spring目录下创建applicationContext-jms-queue.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--公共部分 Start-->
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL"
                  value="tcp://192.168.43.156:61616"/>
        <property name="trustAllPackages" value="true"/>
        <property name="userName" value="admin"></property>
        <property name="password" value="admin"></property>
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>

    <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>
    <!--公共部分 End-->

    <!--队列名称 gblfy_queue_String-->
    <bean id="QUEUE_Str" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="QUEUE_Str"/>
    </bean>

    <!--队列名称 gblfy_queue_list-->
    <bean id="QUEUE_Str_LIST" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="QUEUE_Str_LIST"/>
    </bean>

    <!--队列名称 gblfy_queue_obj-->
    <bean id="QUEUE_OBJ" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="QUEUE_OBJ"/>
    </bean>

    <!--这个是队列目的地,导入索引库-->
    <bean id="QUEUE_MAP" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="QUEUE_MAP"/>
    </bean>

</beans>

5.7.2. 在spring目录下创建applicationContext-jms-topic.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--公共部分 Start-->
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL"
                  value="tcp://192.168.43.156:61616"/>
        <property name="trustAllPackages" value="true"/>
        <property name="userName" value="admin"></property>
        <property name="password" value="admin"></property>
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>

    <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>
    <!--公共部分 End-->

    <!--队列名称 gblfy_queue_String-->
    <bean id="TOPIC_Str" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="TOPIC_Str"/>
    </bean>

    <!--队列名称 gblfy_queue_list-->
    <bean id="TOPIC_Str_LIST" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="TOPIC_Str_LIST"/>
    </bean>

    <!--队列名称 gblfy_queue_obj-->
    <bean id="TOPIC_OBJ" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="TOPIC_OBJ"/>
    </bean>

    <!--这个是队列目的地,导入索引库-->
    <bean id="TOPIC_MAP" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="TOPIC_MAP"/>
    </bean>

</beans>

5.7.3. 在spring目录下创建applicationContext-service.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- spring自动去扫描base-pack下面或者子包下面的java文件-->
    <!--管理Service实现类-->
    <context:component-scan base-package="com.gblfy.mq"/>
</beans>

5.7.4. 在spring目录下创建applicationContext-trans.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- spring自动去扫描base-pack下面或者子包下面的java文件-->
    <!--管理Service实现类-->
    <context:component-scan base-package="com.gblfy.mq"/>
</beans>

5.7.5. 在spring目录下创建spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描controller -->
    <context:component-scan base-package="com.gblfy.mq.controller" />

    <!-- Spring 来扫描指定包下的类,并注册被@Component,@Controller,@Service,@Repository等注解标记的组件 -->
    <mvc:annotation-driven />

    <!-- 配置SpringMVC的视图解析器-->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

5.8. 在resources目录下创建log4j.properties

log4j.rootLogger=error,CONSOLE,A
log4j.addivity.org.apache=false

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=error
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=gbk
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout


log4j.appender.A=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.A.File=${catalina.home}/logs/FH_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout  
log4j.appender.A.layout.ConversionPattern=[FH_sys]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n


5.9. 在resources目录下创建log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy HH:mm:ss} %-5p %c - %m%n" />
        </layout>
    </appender>

    <!-- Application Loggers -->
    <logger name="com">
        <level value="error" />
    </logger>

    <!-- 3rdparty Loggers -->
    <logger name="org.springframework.core">
        <level value="error" />
    </logger>

    <logger name="org.springframework.beans">
        <level value="error" />
    </logger>

    <logger name="org.springframework.context">
        <level value="error" />
    </logger>

    <logger name="org.springframework.web">
        <level value="error" />
    </logger>

    <logger name="org.springframework.jdbc">
        <level value="error" />
    </logger>

    <logger name="org.mybatis.spring">
        <level value="error" />
    </logger>
    <logger name="java.sql">
        <level value="error" />
    </logger>
    <!-- Root Logger -->
    <root>
        <priority value="error" />
        <appender-ref ref="console" />
    </root>

</log4j:configuration>

5.10. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <display-name>producer-web</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- 解决post乱码 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>ssm</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>ssm</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

</web-app>

5.11. 验证测试

5.11.1. 数据库联通测试UserMapperTest

package com.gblfy.mq.mapper;

import com.gblfy.mq.entity.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Arrays;
import java.util.List;

/**
 * 测试互数据库连接
 */
public class UserMapperTest {

    private ApplicationContext ioc =
            new ClassPathXmlApplicationContext("/spring/applicationContext-dao.xml");

    private UserMapper userMapper =
            ioc.getBean("userMapper", UserMapper.class);

    /**
     * 测试数据库连接池
     */
    @Test
    public void testDataSource() throws Exception {
        DataSource ds = ioc.getBean("dataSource", DataSource.class);
        System.out.println(ds);
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }

    /**
     * 查询单个商品操作
     */
    @Test
    public void itemById() {
        User item = userMapper.selectById(1);
        System.out.println("~~~~~~~~~:" + item);
    }

    /**
     * 查询商多个品操作
     */
    @Test
    public void itemListByIds() {
        List<Integer> ids = Arrays.asList(1, 2);
        List<User> itemList = userMapper.selectBatchIds(ids);
        for (User item : itemList) {
            System.out.println("~~~~~~~" + item);
        }
    }

    /**
     * 查询商品列表操作
     */
    @Test
    public void itemList() {
        List<User> itemList = userMapper.selectList(null);
        for (User item : itemList) {
            System.out.println("这是一个测试" + "\n" + item);
        }
    }
}

5.11.2. 点对点测试场景

package com.gblfy.mq.service;

import com.alibaba.fastjson.JSON;
import com.gblfy.mq.entity.User;
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.jms.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/applicationContext-jms-queue.xml")
public class IQueueProductServiceTest {

    @Autowired
    private JmsTemplate jmsQueueTemplate;

    /**
     * 消息类型  List
     */
    @Test
    public void sendStringMessage() {

        Destination destination = new ActiveMQQueue("QUEUE_Str");
        sendListMessage(destination, "send string queue message!!!");
    }

    /**
     * 消息类型  List
     */
    @Test
    public void sendListMessage() {

        Destination destination = new ActiveMQQueue("QUEUE_Str_LIST");
        User user = getObj();
        List<User> userList = getListObj(user);
        //把对象列表转成jsonString
        final String jsonString = JSON.toJSONString(userList);
        sendListMessage(destination, jsonString);
    }


    /**
     * 消息类型 Obj
     */
    @Test
    public void sendObjMessage() {
        Destination destination = new ActiveMQQueue("QUEUE_OBJ");
        User user = getObj();
        sendObjMessage(destination, user);
    }

    /**
     * 消息类型 Map
     */
    @Test
    public void sendMapMessage() {
        String mapKey = "mapKey";
        String mapValue = "mapValue";

        Destination destination = new ActiveMQQueue("QUEUE_MAP");
        sendMapMessage(destination, mapKey, mapValue);
    }

    /**
     * 发送消息类型  String
     *
     * @param destination
     * @param msg
     */
    public void sendStringMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 送消息类型 List
     *
     * @param destination
     * @param msg
     */
    public void sendListMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 发送消息类型 Obj
     *
     * @param destination
     * @param obj
     */
    public void sendObjMessage(Destination destination, final Serializable obj) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(obj);
            }
        });
    }

    /**
     * 发送消息类型 map
     *
     * @param destination
     * @param message
     */
    public void sendMapMessage(Destination destination, final String mapKey, final String message) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString(mapKey, message);
                return mapMessage;
            }
        });
        System.out.println("springJMS send map message...");
    }

    /**
     * 向指定Destination发送字节消息
     *
     * @param destination
     * @param bytes
     */
    public void sendBytesMessage(Destination destination, final byte[] bytes) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(bytes);
                return bytesMessage;

            }
        });
        System.out.println("springJMS send bytes message...");
    }

    /**
     * 向默认队列发送Stream消息
     */
    public void sendStreamMessage(Destination destination) {
        jmsQueueTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                StreamMessage message = session.createStreamMessage();
                message.writeString("stream string");
                message.writeInt(11111);
                return message;
            }
        });
        System.out.println("springJMS send Strem message...");
    }

    /**
     * 封装List
     *
     * @param user
     * @return
     */
    public List<User> getListObj(User user) {
        List<User> userList = new ArrayList<User>();
        userList.add(user);
        return userList;
    }

    /**
     * 封装公用对象
     *
     * @return
     */
    private User getObj() {
        //封装测试数据
        User user = new User().builder()
                .id("1")
                .name("yuxin")
                .age(02)
                .build();
        return user;
    }
}

5.11.3. 发布订阅测试场景

package com.gblfy.mq.service;

import com.alibaba.fastjson.JSON;
import com.gblfy.mq.entity.User;
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.jms.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/applicationContext-jms-topic.xml")
public class ITopicProductServiceTest {

    @Autowired
    private JmsTemplate jmsQueueTemplate;

    /**
     * 消息类型  List
     */
    @Test
    public void sendStringMessage() {

        Destination destination = new ActiveMQQueue("TOPIC_Str");
        sendListMessage(destination, "send string queue message!!!");
    }

    /**
     * 消息类型  List
     */
    @Test
    public void sendListMessage() {

        Destination destination = new ActiveMQQueue("TOPIC_Str_LIST");
        User user = getObj();
        List<User> userList = getListObj(user);
        //把对象列表转成jsonString
        final String jsonString = JSON.toJSONString(userList);
        sendListMessage(destination, jsonString);
    }


    /**
     * 消息类型 Obj
     */
    @Test
    public void sendObjMessage() {
        Destination destination = new ActiveMQQueue("TOPIC_OBJ");
        User user = getObj();
        sendObjMessage(destination, user);
    }

    /**
     * 消息类型 Map
     */
    @Test
    public void sendMapMessage() {
        String mapKey = "mapKey";
        String mapValue = "mapValue";

        Destination destination = new ActiveMQQueue("TOPIC_MAP");
        sendMapMessage(destination, mapKey, mapValue);
    }

    /**
     * 发送消息类型  String
     *
     * @param destination
     * @param msg
     */
    public void sendStringMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 送消息类型 List
     *
     * @param destination
     * @param msg
     */
    public void sendListMessage(Destination destination, final String msg) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 发送消息类型 Obj
     *
     * @param destination
     * @param obj
     */
    public void sendObjMessage(Destination destination, final Serializable obj) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(obj);
            }
        });
    }

    /**
     * 发送消息类型 map
     *
     * @param destination
     * @param message
     */
    public void sendMapMessage(Destination destination, final String mapKey, final String message) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString(mapKey, message);
                return mapMessage;
            }
        });
        System.out.println("springJMS send map message...");
    }

    /**
     * 向指定Destination发送字节消息
     *
     * @param destination
     * @param bytes
     */
    public void sendBytesMessage(Destination destination, final byte[] bytes) {
        if (null == destination) {
            destination = jmsQueueTemplate.getDefaultDestination();
        }
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(bytes);
                return bytesMessage;

            }
        });
        System.out.println("springJMS send bytes message...");
    }

    /**
     * 向默认队列发送Stream消息
     */
    public void sendStreamMessage(Destination destination) {
        jmsQueueTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                StreamMessage message = session.createStreamMessage();
                message.writeString("stream string");
                message.writeInt(11111);
                return message;
            }
        });
        System.out.println("springJMS send Strem message...");
    }

    /**
     * 封装List
     *
     * @param user
     * @return
     */
    public List<User> getListObj(User user) {
        List<User> userList = new ArrayList<User>();
        userList.add(user);
        return userList;
    }

    /**
     * 封装公用对象
     *
     * @return
     */
    private User getObj() {
        //封装测试数据
        User user = new User().builder()
                .id("1")
                .name("yuxin")
                .age(02)
                .build();
        return user;
    }

}

下一篇:实战06_SSM整合ActiveMQ支持多种类型消息https://blog.csdn.net/weixin_40816738/article/details/100572147

本专栏项目下载链接:

下载方式链接详细
GitLab项目https://gitlab.com/gb-heima/ssm-activemq
Gitgit clone git@gitlab.com:gb-heima/ssm-activemq.git
zip包https://gitlab.com/gb-heima/ssm-activemq/-/archive/master/ssm-activemq-master.zip
Fork地址https://gitlab.com/gb-heima/ssm-activemq/-/forks/new
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

<p> <span style="color:#333333;"><strong></strong></span> </p> <span style="font-size:24px;">一、简介</span> <p> <span style="font-size:12px;"></span> </p> <p> <span style="font-size:16px;">通过这个课程带大家从零开发一款功能全面的后台管理系统,包括项目搭建、功能实现到最后的Linux系统部署全过程。本课程使用SpringMVC + Spring + Mybatis作为主体框架,使用AdminLTE作为前端框架,使用主流关系型数据库Mysql作为存储数据库,使用非关系型数据库Redis作为缓存数据库,并集成SpringSecuriy安全框架做权限的动态管理,集成Swagger2自动生成接口文档,集成Druid连接池进行SQL性能监控,集成ActiveMQ消息中间件进行异步解耦,提高性能。最后使用linux系统进行服务部署,并搭建nginx反向代理服务器提高网站性能。</span> </p> <p> <br /> </p> <p> <span style="font-size:24px;"><strong>二、学习目标</strong></span> </p> <p> <span style="font-size:16px;">通过本课程的学习带大家掌握SSM框架的开发流程,并熟练使用SpringSecurity做为安全框架进行权限管理,整合相关优秀的开源框架进行功能开发。还在项目中带大家学习前端相关的Jquery、Bootstrap等知识。课程结束之后希望大家能做到独立进行开发项目的目的,增强解决问题的能力,具备功能落地实现的能力。</span> </p> <p> <span style="font-size:16px;"><span style="font-size:24px;"><strong>三、课程涉及知识点</strong></span></span> </p> <p> <span style="font-size:16px;"></span> </p> <ul> <li> SpringMVC源码分析 </li> <li> Mybatis源码分析 </li> <li> 通用Mapper </li> <li> Mysql数据库 </li> <li> Redis缓存实现 </li> <li> ActiveMQ消息中间件 </li> <li> SpringSecurity鉴权 </li> <li> Swagger2接口文档生成 </li> <li> 自定义注解 </li> <li> AOP切面编程 </li> <li> 自定义过滤器 </li> <li> Logback日志整合 </li> <li> Druid性能监控 </li> <li> Linux系统 </li> <li> Nginx反向代理 </li> <li> Ajax异步请求技术 </li> <li> Jquery基本使用 </li> <li> AdminLTE前端框架 </li> <li> Chart图表-线状图和饼状图 </li> <li> 百度地图定位城市 </li> <li> BootStrap前端框架 </li> <li> BootStrap-Table插件 </li> <li> BootStrap-Treeview插件 </li> <li> Markdown编辑器 </li> <li> 403、404、500错误页面配置 </li> <li> 数据库事务 </li> <li> 消息提示插件toastr.js </li> <li> 图片上传插件bootstrap fileinput </li> <li> 数字滚动效果 </li> <li> pv/uv流量统计 </li> <li> ... </li> </ul> <p> <br /> </p> <p> <span style="font-size:16px;"><span style="font-size:24px;"><strong>四、</strong></span><span style="font-size:24px;"><strong>课程部分内容截图如下</strong></span><span style="font-size:24px;"><strong></strong></span></span> </p> <p> <span style="font-size:18px;"><span style="font-size:18px;"><strong>1、首页</strong></span></span> </p> <p> <span style="font-size:16px;"><span style="font-size:24px;"><strong><span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MTkvMjAxOTA5MTkxMTE1MTJfMTM5LnBuZw?x-oss-process=image/format,png" /></span></strong></span></span> </p> <p> <span style="font-size:24px;"><span style="font-size:24px;"><strong><span style="font-size:24px;">2、菜单管理</span></strong></span></span> </p> <p> <span style="font-size:24px;"><span style="font-size:24px;"><strong><span style="font-size:24px;"><span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MTkvMjAxOTA5MTkxMTE3MjBfNzE5LnBuZw?x-oss-process=image/format,png" /></span><br /> </span></strong></span></span> </p> <p> <span></span> </p> <p> <span><span style="font-size:24px;"><strong>3、图床管理</strong></span><span style="font-size:24px;"><strong></strong></span><br /> </span> </p> <p> <span><span style="font-size:24px;"><strong><span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MTkvMjAxOTA5MTkxMTIwMTJfNjYwLnBuZw?x-oss-process=image/format,png" /><span></span></span><span></span><br /> </strong></span></span> </p> <p> <span><span style="font-size:24px;"><strong>4、图标管理<br /> </strong></span></span> </p> <p> <span><span style="font-size:24px;"><strong><span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MTkvMjAxOTA5MTkxMTIxMDBfMTcucG5n?x-oss-process=image/format,png" /><span></span></span><span></span></strong></span></span> </p> <p> <span><span style="font-size:24px;"><strong>5、留言反馈管理<br /> </strong></span></span> </p> <p> <span><span style="font-size:24px;"><strong><span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MjEvMjAxOTA5MjExMDEwMTJfMzQ2LnBuZw?x-oss-process=image/format,png" /><span></span></span><span></span></strong></span></span> </p> <p> <span><span style="font-size:24px;"><strong>6、druid监控<br /> </strong></span></span> </p> <p> <span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MTkvMjAxOTA5MTkxMTIzMzVfNTgwLnBuZw?x-oss-process=image/format,png" /></span> </p> <p> <br /> </p> <p> <span style="font-size:24px;"><strong></strong></span><span style="font-size:24px;"><strong>7、登录日志</strong></span><span style="font-size:24px;"><strong></strong></span> </p> <p> <span style="font-size:24px;"><strong><span></span><span><img alt="" src="https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy5kcmVhbWxhbmQud2FuZy9pbWFnZXMvaW1hZ2UvMjAxOTA5MTkvMjAxOTA5MTkxMTI0MzJfOTQyLnBuZw?x-oss-process=image/format,png" /><span></span></span><span></span><br /> </strong></span> </p> <p> <br /> </p>
相关推荐
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值