开发需求:用于ERP业务员给商城商品调价
依赖注入
<!-- activemq begin -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<!-- activemq end -->
商品调价队列的发送端
import com.alibaba.fastjson.JSON;
import com.meishi.basic.web.modules.api.vo.ProductsPriceAdjustSendEntity;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import javax.jms.*;
/**
* 商品调价发送端
*
* @author WYP
*/
public class ProductsPriceAdjustSender {
protected Logger logger = LogManager.getLogger(getClass());
public void sendMessage(ProductsPriceAdjustSendEntity senderEntity) {
String userName = "admin";
String password = "admin";
String brokerURL = "tcp://192.168.3.17:61616";
String queueName = "item.queue";
try {
ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, brokerURL);
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
//从session中,获取一个消息生产者
MessageProducer producer = session.createProducer(destination);
//设置生产者的模式,有两种可选
//DeliveryMode.PERSISTENT 当activemq关闭的时候,队列数据将会被保存
//DeliveryMode.NON_PERSISTENT 当activemq关闭的时候,队列里面的数据将会被清空
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
//创建一条消息,当然,消息的类型有很多,如文字,字节,对象等,可以通过session.create..方法来创建出来
String sendMsg = JSON.toJSONString(senderEntity);
TextMessage msg = session.createTextMessage(sendMsg);
//发送一条消息
producer.send(msg);
logger.info("发送成功!" + sendMsg);
//即便生产者的对象关闭了,程序还在运行
producer.close();
} catch (JMSException e) {
logger.info("发送失败!" + e);
e.printStackTrace();
}
}
}