Active MQ 发送消息

开发需求:用于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();
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值