阿里rocketMq发送消息队列

1、maven依赖:

     <dependency>
            <groupId>com.aliyun.openservices</groupId>
            <artifactId>ons-client</artifactId>
            <version>1.7.9.Final</version>
        </dependency>

2、发送消息util:


import com.aliyun.openservices.ons.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * 发送阿里云队列消息 --- RabbitMq
 * @author zhangxb
 */
@Component
public class AliRabbitMqUtil {

    public static Logger logger = LoggerFactory.getLogger(AliRabbitMqUtil.class);
    public Properties properties = new Properties();
    @Autowired
    private Environment env;

    public static String AL_RABBITMQ_GROUP_ID;

    public static String AL_RABBITMQ_ACCESSKEY;

    public static String AL_RABBITMQ_SECRETKEY;

    public static String AL_RABBITMQ_SENDMSGTIMEOUTMILLIS;

    public static String AL_RABBITMQ_NAMESRV_ADDR;

    public static String AL_RABBITMQ_TOPIC;

    public static String AL_RABBITMQ_TAGS;

    @PostConstruct
    public void readConfig() {
        AL_RABBITMQ_GROUP_ID = env.getProperty("AL_RABBITMQ_GROUP_ID");
        AL_RABBITMQ_ACCESSKEY = env.getProperty("AL_RABBITMQ_ACCESSKEY");
        AL_RABBITMQ_SECRETKEY = env.getProperty("AL_RABBITMQ_SECRETKEY");
        AL_RABBITMQ_SENDMSGTIMEOUTMILLIS = env.getProperty("AL_RABBITMQ_SENDMSGTIMEOUTMILLIS");
        AL_RABBITMQ_NAMESRV_ADDR = env.getProperty("AL_RABBITMQ_NAMESRV_ADDR");
        AL_RABBITMQ_TOPIC = env.getProperty("AL_RABBITMQ_TOPIC");
        AL_RABBITMQ_TAGS = env.getProperty("AL_RABBITMQ_TAGS");
    }


    private AliRabbitMqUtil(){}
    private static AliRabbitMqUtil aliRabbitMqUtil=null;
    public static AliRabbitMqUtil getInstance(){
        if(aliRabbitMqUtil == null){
            aliRabbitMqUtil = new AliRabbitMqUtil();
        }
        return aliRabbitMqUtil;
    }
    public void sendRabbitMQMessage(String message,String setKey){
        properties.setProperty(PropertyKeyConst.GROUP_ID, AL_RABBITMQ_GROUP_ID);
        // AccessKey 阿里云身份验证,在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.AccessKey, AL_RABBITMQ_ACCESSKEY);
        // SecretKey 阿里云身份验证,在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, AL_RABBITMQ_SECRETKEY);
        //设置发送超时时间,单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, AL_RABBITMQ_SENDMSGTIMEOUTMILLIS);
        // 设置 TCP 接入域名,到控制台的实例基本信息中查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,AL_RABBITMQ_NAMESRV_ADDR);

        Producer producer = ONSFactory.createProducer(properties);
        // 在发送消息前,必须调用 start 方法来启动 Producer,只需调用一次即可
        producer.start();

        Message msg = new Message(
                // Message 所属的 Topic
                AL_RABBITMQ_TOPIC,
                // Message Tag 可理解为 Gmail 中的标签,对消息进行再归类,方便 Consumer 指定过滤条件在 MQ 服务器过滤
                AL_RABBITMQ_TAGS,
                // Message Body 可以是任何二进制形式的数据, MQ 不做任何干预,
                // 需要 Producer 与 Consumer 协商好一致的序列化和反序列化方式
                message.getBytes());
        // 设置代表消息的业务关键属性,请尽可能全局唯一。
        // 以方便您在无法正常收到消息情况下,可通过阿里云服务器管理控制台查询消息并补发
        // 注意:不设置也不会影响消息正常收发
        msg.setKey("ORDERID_" + setKey);
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        try {
            SendResult sendResult = producer.send(msg);
            // 同步发送消息,只要不抛异常就是成功
            if (sendResult != null) {
                logger.info(date + " Send mq message success. Topic is:" + msg.getTopic() + " OrderID is: " + setKey);
            }
        } catch (Exception e) {
            // 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理
            logger.error(new Date() + " Send mq message failed. Topic is:" + msg.getTopic());
            DingDingMessageUtil.sendTextMessage("异常时间:"+date + "\n 服务名:provider"+"\n MQ-阿里订单信息发送失败. \n Topic is:" + msg.getTopic() + "\n 订单号: " + setKey);
            e.printStackTrace();
        }

        // 在应用退出前,销毁 Producer 对象
        // 注意:如果不销毁也没有问题
        producer.shutdown();
    }
}

3、调用工具类发送消息:

AliRabbitMqUtil.getInstance().sendRabbitMQMessage(messageo.toString(),orderid);

 

简单发送消息队列写法:

import com.aliyun.openservices.ons.api.*;
import com.ycb.socket.zk.AppSecretConfig;

import java.util.Properties;

public class RocketMqProducer {

	public static void sendQueueMsg(String groupId,String topicName,byte[] bytes,String tag){
		Properties properties = new Properties();
        // 您在控制台创建的 Group ID
        properties.put(PropertyKeyConst.GROUP_ID, groupId);
        // 鉴权用的 RAM 子账号的 AccessKeyId,由主账号创建,请向主账号获取
        properties.put(PropertyKeyConst.AccessKey,AppSecretConfig.get().ACCESSKEY);
        // 鉴权用的 RAM 子账号的 AccessKeySecret,由主账号创建,请向主账号获取
        properties.put(PropertyKeyConst.SecretKey, AppSecretConfig.get().SECRETKEY);
        // 设置 TCP 接入域名,进入控制台的实例管理页面,在页面上方选择实例后,在实例信息中的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,AppSecretConfig.get().NAMESRV_ADDR);
        Producer producer = ONSFactory.createProducer(properties);
        // 在发送消息前,必须调用 start 方法来启动 Producer,只需调用一次即可
        producer.start();
     // 在控制台创建的 Topic,即该消息所属的 Topic 名称
     // Message Tag,可理解为 Gmail 中的标签,对消息进行再归类,方便 Consumer 指定过滤条件在消息队列 RocketMQ 服务器过滤
     // Message Body任何二进制形式的数据, 消息队列 RocketMQ 不做任何干预,
        Message msg = new Message(topicName,tag,bytes);
        SendResult sendResult = producer.send(msg);
        System.out.println("Send Message success. Message ID is: " + sendResult.getMessageId());
        producer.shutdown();
	}
	
	


}

简单消费写法:

package com.thinkgem.jeesite.modules.rocketmq;

import java.util.Properties;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.thinkgem.jeesite.common.config.Global;

public class RocketMqConsumer {

	public static void getQueueMsg(String groupId,String topicName,String tag){
		
		Properties properties = new Properties();
        // 您在控制台创建的 Group ID
        properties.put(PropertyKeyConst.GROUP_ID, groupId);
        // 鉴权用的 RAM 子账号的 AccessKeyId,由主账号创建,请向主账号获取
        properties.put(PropertyKeyConst.AccessKey,Global.getConfig("AccessKey"));
        // 鉴权用的 RAM 子账号的 AccessKeySecret,由主账号创建,请向主账号获取
        properties.put(PropertyKeyConst.SecretKey, Global.getConfig("SecretKey"));
        // 设置 TCP 接入域名,进入控制台的实例管理页面,在页面上方选择实例后,在实例信息中的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,Global.getConfig("NAMESRV_ADDR"));
        Consumer consumer = ONSFactory.createConsumer(properties);
        
        consumer.subscribe(topicName, tag, new MessageListener() {
            public Action consume(Message message, ConsumeContext context) {
                System.out.println("Receive: " + new String(message.getBody()));
                
//                Cat cat = (Cat) ByteArrayUtils.bytesToObject(message.getBody()).get();
//                
//                System.out.println("消费者===》"+cat.getName()+"---"+cat.getColor()+"---"+cat.getHight()+"---"+cat.getWeight());
                
                return Action.CommitMessage;
            }
        });
        consumer.start();
        System.out.println("Consumer Started");
	}
	
	
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值