Servlet中使用ActiveMQ报错javax.jms.JMSException: Cannot send, channel has alr...
本帖最后由 majunwang 于 2023-4-27 10:04 编辑import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.*;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.IOException;
@WebServlet(name = "SendOrderServlet", value = "/SendOrderServlet")
public class SendOrderServlet extends HttpServlet {
private Connection connection;
private Session session;
private MessageProducer messageProducer;
private void setup() throws JMSException {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://10.100.164.50:61616");
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("order-queue");
messageProducer = session.createProducer(queue);
connection.start();
}
private void sendMessage(String message) throws JMSException {
TextMessage textMessage = session.createTextMessage(message);
messageProducer.send(textMessage);
}
private void cleanup() throws JMSException {
if (messageProducer != null) {
messageProducer.close();
}
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
}
@Override
public void init() throws ServletException {
super.init();
try {
setup();
} catch (JMSException e) {
throw new ServletException("初始化producer失败!", e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String orderId = request.getParameter("order_id");
String productName = request.getParameter("product_name");
int quantity = Integer.parseInt(request.getParameter("quantity"));
float price = Float.parseFloat(request.getParameter("price"));
String address = request.getParameter("address");
Order order = new Order(orderId, productName, quantity, price, address);
String orderJSON = JSONObject.toJSONString(order);
String result = "发送成功!";
try {
sendMessage(orderJSON);
} catch (Exception e) {
result = "发送失败!原因:" + e;
}
request.setAttribute("result", result);
request.getRequestDispatcher("/send_orders.jsp").forward(request, response);
}
@Override
public void destroy() {
super.destroy();
try {
cleanup();
} catch (JMSException e) {
log("Failed to clean up producer", e);
}
}
}
端口被占用? https://blog.csdn.net/weixin_43705313/article/details/105517778 本帖最后由 majunwang 于 2023-4-27 10:10 编辑
已经解决了,有个hawtbuff-1.11.jar没有加进去,不太清楚这个包干嘛的{:1_908:}
页:
[1]