本例子是模拟下订单的,结合 Spring、SpringMVC 整合的 ActiveMQ。
CREATE TABLE `tb_cart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`goods_id` int(11) NOT NULL COMMENT '商品 id',
`goods_quantity` int(11) NOT NULL COMMENT '商品数量',
`goods_price` int(11) NOT NULL COMMENT '价格',
`customer_id` int(11) NOT NULL COMMENT '用户 id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `tb_cart` VALUES ('1', '1', '1', '10', '1');
CREATE TABLE `tb_customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `tb_customer` VALUES ('1', 'yz');
CREATE TABLE `tb_goods` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL COMMENT '商品名称',
`price` int(11) NOT NULL COMMENT '价格',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `tb_goods` VALUES ('1', '旺仔小馒头', '10');
CREATE TABLE `tb_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`customer_id` int(11) NOT NULL COMMENT '顾客 id',
`create_date` date NOT NULL COMMENT '创建时间',
`total_money` int(11) NOT NULL COMMENT '总价',
`status` int(1) NOT NULL COMMENT '状态',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1131 DEFAULT CHARSET=utf8;
CREATE TABLE `tb_stock` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`goods_id` int(11) NOT NULL COMMENT '商品 id',
`stock` int(11) NOT NULL COMMENT '库存',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `tb_stock` VALUES ('1', '1', '1000');
<dependency>
<groupId>org.apache.activemqgroupId>
<artifactId>activemq-poolartifactId>
<version>5.9.0version>
dependency>
<dependency>
<groupId>org.apache.activemqgroupId>
<artifactId>activemq-allartifactId>
<version>5.10.0version>
dependency>
<dependency>
<groupId>org.apache.geronimo.specsgroupId>
<artifactId>geronimo-servlet_3.0_specartifactId>
<version>1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.apache.geronimo.specsgroupId>
<artifactId>geronimo-jms_1.1_specartifactId>
<version>1.1.1version>
dependency>
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class QueueSender{
private static ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://182.254.246.166:61616");
public static void sendMsg(int customerId) {
Connection connection = null;
Session session = null;
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("order-queue");
MessageProducer producer = session.createProducer(destination);
producer.send(session.createTextMessage(customerId + ""));
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
try {
if (null != session) {
session.close();
}
if (null != connection) {
connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.alibaba.fastjson.JSON;
import com.p7.framework.entity.Order;
import com.p7.framework.service.CartService;
import com.p7.framework.service.OrderService;
import com.p7.framework.service.StockService;
/**
*
* 消息消费者实现 监听,使服务启动时,立即调用 consumeMsg 方法
*/
@Service
public class QueueReceive implements ServletContextListener {
@Autowired
private OrderService orderService;
@Autowired
private StockService stockService;
@Autowired
private CartService cartService;
private static ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://182.254.246.166:61616");
public void consumeMsg() {
// 创建 10 个线程,run 方法中使用 activemq 的监听模式,使线程保持监听而不会销毁
for (int i = 0; i < 10; i++) {
new OrderThread(orderService, stockService, cartService, connectionFactory).start();
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
QueueReceive bean = (QueueReceive) context.getBean("queueReceive");
bean.consumeMsg();
}
}
/**
*
* 模拟并发
*/
class OrderThread extends Thread {
private OrderService orderService;
private StockService stockService;
private CartService cartService;
private ConnectionFactory connectionFactory;
public OrderThread(OrderService orderService, StockService stockService, CartService cartService,
ConnectionFactory connectionFactory) {
this.cartService = cartService;
this.orderService = orderService;
this.stockService = stockService;
this.connectionFactory = connectionFactory;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "------");
Connection connection = null;
final Session session;
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("order-queue");
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
TextMessage msg = (TextMessage) message;
String customerId = msg.getText();
session.commit();
System.out.println(Thread.currentThread().getName() + "------处理时间:" + JSON.toJSON(new Date()));
List
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:config/spring/applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<listener>
<listener-class>com.p7.framework.ordermq.QueueReceivelistener-class>
listener>
/** 接口 */
import java.util.List;
import java.util.Map;
public interface CartService {
/**
* 根据客户 id 查询购物车信息
* @param customerId
* @return
*/
List
/** 接口 */
import com.p7.framework.entity.Order;
public interface OrderService {
void createOrder(Order order);
}
/** 接口实现 */
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import com.p7.framework.entity.Order;
import com.p7.framework.service.OrderService;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
public void createOrder(Order order) {
Map map = order.toMap();
jdbcTemplate.update(
"insert into tb_order(customer_id,create_date,total_money,status) values(:customer_id , :create_date , :total_money , :status )",
map);
}
}
/** 接口 */
package com.p7.framework.service;
public interface StockService {
void decrease(String goodsId, int num);
}
/** 接口实现 */
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import com.p7.framework.service.StockService;
@Service
public class StockServiceImpl implements StockService {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
public void decrease(String goodsId, int num) {
Map params = new HashMap();
params.put("goodsId", goodsId);
Map resultMap = jdbcTemplate.queryForMap("select stock from tb_stock where goods_id=:goodsId ",
params);
Integer stock = Integer.parseInt(resultMap.get("stock").toString());
params.put("stock", stock - num);
jdbcTemplate.update("update tb_stock set stock=:stock where goods_id=:goodsId ", params);
}
}