ActiveMQ 设计开发(Queue模式)

package com.jshx.cc.queues;

/**
* 即时通信息发送方queue模式
* @author
*/
import java.io.IOException;
import java.util.Date;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jshx.cc.common.btnpermission.BeanProvider;
import com.jshx.cc.instantMessage.entity.TinstantMessage;
import com.jshx.cc.instantMessage.service.TinstantMessageService;
import com.jshx.module.admin.entity.User;
import com.jshx.module.admin.service.UserService;

public class ActivemqSender extends HttpServlet{

private static final String user = ActiveMQConnection.DEFAULT_USER;
private static final String password = ActiveMQConnection.DEFAULT_PASSWORD;
private static final String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private static final String queueName = "firstQueue";

@Autowired
private UserService userService;

@Autowired
private TinstantMessageService messageService;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
        Connection connection = null;
        Session session = null;
        Queue queue;
        MessageProducer producer;
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user,password,url);
       
        userService = BeanProvider.getBean("userService");//获取userService对象
       
        messageService = BeanProvider.getBean("tinstantMessageService");
        try {
            String sendContent = request.getParameter("chatContent"); // 发送内容
            String loginUserId = request.getParameter("sendUserId"); // 当前登录用户ID
            String receivcerId = request.getParameter("recevicer"); // 接受消息方ID
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            connection.start();
            // 获取操作连接
            session = connection.createSession(Boolean.TRUE,Session.SESSION_TRANSACTED); // modify by hhc 修改事务控制 优化性能
            queue = session.createQueue(queueName);
            producer = session.createProducer(queue);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);// 设置非持久化,设置异步消息发送优化性能 modify by hhc
            // 构造消息,此处写死
            MapMessage message = session.createMapMessage();
            message.setStringProperty("content", sendContent);
            message.setStringProperty("receivcerId", receivcerId);
            message.setStringProperty("loginUserId", loginUserId);
            User user = userService.findUserById(loginUserId);
            if(user != null){
            message.setStringProperty("LoginUserName", user.getDisplayName());//保存发送人的姓名
            message.setStringProperty("LoginId", user.getLoginId());//保存发送人的登录名
            }
            // 发送消息到目的地
            Thread.sleep(1000);
            producer.send(message);
            System.out.println(user.getDisplayName()+"--发送的消息是--" + sendContent);
            // 消息入库
            TinstantMessage tMessage = new TinstantMessage();
            tMessage.setSenderID(loginUserId);
            tMessage.setReceiverID(receivcerId);
            tMessage.setContent(sendContent);
            tMessage.setDelFlag(0);
            tMessage.setCreateTime(new Date());
            tMessage.setUpdateTime(new Date());
            tMessage.setCreateUserID(loginUserId);
            tMessage.setUpdateUserID(loginUserId);
            messageService.save(tMessage);
            session.commit();
           
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
            if (null != session){
            session.close();
        }
                if (null != connection){
                connection.close();
                }
            } catch (Exception e) {
            e.printStackTrace();
            }
        }
    }
   
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        processRequest(request, response); 
    }  
 
    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        processRequest(request, response); 
    }
}
package com.jshx.cc.queues;

/**
* 即时通信消息接受方queue模式
* @author
*/
import java.io.IOException;
import java.io.PrintWriter;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ActivemqReceiver extends HttpServlet{

private static final String user = ActiveMQConnection.DEFAULT_USER;
private static final String password = ActiveMQConnection.DEFAULT_PASSWORD;
private static final String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private static final String queueName = "firstQueue";

protected void processResponse(HttpServletRequest request, HttpServletResponse response) {
String loginUserId = request.getParameter("sendUserId"); // 当前登录用户ID
String receivcerId = request.getParameter("recevicer"); // 接受消息方ID
        Connection connection = null;
        final Session session;
        Queue queue;
        MessageConsumer consumer;
       
        // 内嵌broker 超快回应消息 优化性能
        /*BrokerService broker = new BrokerService();
        broker.setBrokerName("service");
        broker.setPersistent(false);
        try {
broker.addConnector("tcp://localhost:61616");
broker.start();
} catch (Exception e2) {
e2.printStackTrace();
}*/

// ConnectionFactory :连接工厂,创建JMS连接
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user,password,url);
        try {
        final PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        response.setContentType("text/html"); 
            response.setHeader("Cache-Control", "no-store"); 
            response.setHeader("Pragma", "no-cache"); 
            response.setDateHeader("Expires", 0);
        // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            connection.start();
            // 获取操作连接
            session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            queue = session.createQueue(queueName);
            consumer = session.createConsumer(queue,"receivcerId="+"'"+receivcerId+"'"+" and loginUserId="+"'"+loginUserId+"'"); // 使用同一个队列需要添加过滤条件
            consumer.setMessageListener(new MessageListener(){
public void onMessage(Message msg){
if(msg != null){
MapMessage message = (MapMessage)msg;
try{
System.out.println("---收到消息--->"+message.getStringProperty("content"));
out.println(message.getStringProperty("content"));
session.commit();
}catch(JMSException e){
e.printStackTrace();
}finally{
if (null != session){
            try {
session.close();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
}
}
}
});
            Thread.sleep(1000); //休眠1秒
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        try {
        if (null != connection){
connection.close();
                }
                } catch (JMSException e) {
e.printStackTrace();
}
            }
        }

@Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
processResponse(request, response); 
    }  
 
    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    processResponse(request, response); 
    }
}

package com.jshx.cc.queues;

/**
* 即时通信查询不消费(页面消息提醒类)
* @author
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ActivemqQuery extends HttpServlet{

private static final String user = ActiveMQConnection.DEFAULT_USER;
private static final String password = ActiveMQConnection.DEFAULT_PASSWORD;
private static final String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private static final String queueName = "firstQueue";

@SuppressWarnings("unchecked")
protected void processResponse(HttpServletRequest request, HttpServletResponse response) {

String receivcerId = request.getParameter("recevicer"); // 接受消息方ID
        // ConnectionFactory :连接工厂,创建JMS连接
        ConnectionFactory connectionFactory;
        // Connection :JMS 客户端到JMS Provider 的连接
        Connection connection = null;
        // Session: 一个发送或接收消息的线程
        final Session session;
        // Destination :消息的目的地;消息发送给谁.
        Destination destination;
        // 消费者,消息接收者
        MessageConsumer consumer;
        //查询消息
        QueueBrowser queueBrowser;
       
        connectionFactory = new ActiveMQConnectionFactory(user,password,url);
       
        try {
        final PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        response.setContentType("text/html"); 
            response.setHeader("Cache-Control", "no-store"); 
            response.setHeader("Pragma", "no-cache"); 
            response.setDateHeader("Expires", 0);
        // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
            destination = session.createQueue(queueName);
            //此queueBrowser可以查看队列中的消息,但不会消费掉。
            queueBrowser = session.createBrowser(session.createQueue(queueName),"receivcerId='"+receivcerId+"'");
            Enumeration<?> enumeration = queueBrowser.getEnumeration();
            JSONArray jsonArr = new JSONArray();
            while (enumeration.hasMoreElements()) {
            MapMessage message = (MapMessage) enumeration.nextElement();
            if(message != null){
            JSONObject json = new JSONObject();
            json.put("content", message.getStringProperty("content"));
            json.put("receivcerId", message.getStringProperty("receivcerId"));
            json.put("loginUserId", message.getStringProperty("loginUserId"));
            json.put("LoginUserName", message.getStringProperty("LoginUserName"));
            json.put("LoginId", message.getStringProperty("LoginId"));
            jsonArr.add(json);
            System.out.println("存在接收人是当前登录人的消息-->" + message.getStringProperty("content"));
            break;
            }
           
            }
            if(jsonArr.size() > 0){
            System.out.println("消息查询结束...正在返回结果到页面.......");
            out.write(jsonArr.toString());
            }else{
            out.write("");
            }
           
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }

@Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
processResponse(request, response); 
    }  
 
    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    processResponse(request, response); 
    }
}

你可能感兴趣的:(servlet,jms,activemq)