参考文档:https://help.aliyun.com/product/29530.html?spm=a2c4g.11186623.6.540.3cc87b4arGmtrs
com.aliyun.openservices
ons-client
1.7.9.Final
二、登录阿里云创建topic,授权,创建groupID,获取用户key
三、代码
1、生产者配置类
import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
@Configuration
@EnableJms
public class AliyunMqProducerConfig {
@Value("${aliyun.mq.accessKey}")
private String accessKey;
@Value("${aliyun.mq.secretKey}")
private String secretKey;
@Value("${aliyun.mq.namesrvAddr}")
private String namesrvAddr;
@Bean(initMethod = "start", destroyMethod = "shutdown")
public ProducerBean producerBean() {
Properties properties = new Properties();
// 鉴权用 AccessKey,在阿里云服务器管理控制台创建
properties.put(PropertyKeyConst.AccessKey, accessKey);
// 鉴权用 SecretKey,在阿里云服务器管理控制台创建
properties.put(PropertyKeyConst.SecretKey, secretKey);
// 设置 TCP 接入域名(此处以公共云的公网接入为例)
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
properties.put(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
ProducerBean producerBean = new ProducerBean();
producerBean.setProperties(properties);
return producerBean;
}
}
2、生产者类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendCallback;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
@Component
public class AliyunMqProducer {
private static final Logger logger = LoggerFactory.getLogger(AliyunMqProducer.class);
@Autowired
private ProducerBean producerBean;
public SendResult send(String topic, String key, byte[] body) {
return this.send(topic, null, key, body);
}
public SendResult send(String topic, String tag, String key, byte[] body) {
logger.info(String.format("send() input: topic = %s, tag = %s, key = %s, body length = %s", topic, tag, key,
body.length));
Message message = new Message(
// 在控制台创建的 Topic,即该消息所属的 Topic 名称
topic,
// Message Tag,
// 可理解为 Gmail 中的标签,对消息进行再归类,方便 Consumer 指定过滤条件在 MQ 服务器过滤
tag,
// Message Body
// 任何二进制形式的数据, MQ 不做任何干预,
// 需要 Producer 与 Consumer 协商好一致的序列化和反序列化方式
body);
// 设置代表消息的业务关键属性,请尽可能全局唯一,以方便您在无法正常收到消息情况下,可通过 MQ 控制台查询消息并补发
// 注意:不设置也不会影响消息正常收发
message.setKey(key);
return this.producerBean.send(message);
}
public void sendOneway(String topic, String key, byte[] body) {
this.sendOneway(topic, null, key, body);
}
public void sendOneway(String topic, String tag, String key, byte[] body) {
logger.info(String.format("send() input: topic = %s, tag = %s, key = %s, body length = %s", topic, tag, key,
body.length));
Message message = new Message(
// 在控制台创建的 Topic,即该消息所属的 Topic 名称
topic,
// Message Tag,
// 可理解为 Gmail 中的标签,对消息进行再归类,方便 Consumer 指定过滤条件在 MQ 服务器过滤
tag,
// Message Body
// 任何二进制形式的数据, MQ 不做任何干预,
// 需要 Producer 与 Consumer 协商好一致的序列化和反序列化方式
body);
// 设置代表消息的业务关键属性,请尽可能全局唯一,以方便您在无法正常收到消息情况下,可通过 MQ 控制台查询消息并补发
// 注意:不设置也不会影响消息正常收发
message.setKey(key);
this.producerBean.sendOneway(message);
}
public void sendAsync(String topic, String key, byte[] body, SendCallback sendCallback) {
this.sendAsync(topic, null, key, body, sendCallback);
}
public void sendAsync(String topic, String tag, String key, byte[] body, SendCallback sendCallback) {
logger.info(String.format("send() input: topic = %s, tag = %s, key = %s, body length = %s", topic, tag, key,
body.length));
Message message = new Message(
// 在控制台创建的 Topic,即该消息所属的 Topic 名称
topic,
// Message Tag,
// 可理解为 Gmail 中的标签,对消息进行再归类,方便 Consumer 指定过滤条件在 MQ 服务器过滤
tag,
// Message Body
// 任何二进制形式的数据, MQ 不做任何干预,
// 需要 Producer 与 Consumer 协商好一致的序列化和反序列化方式
body);
// 设置代表消息的业务关键属性,请尽可能全局唯一,以方便您在无法正常收到消息情况下,可通过 MQ 控制台查询消息并补发
// 注意:不设置也不会影响消息正常收发
message.setKey(key);
this.producerBean.sendAsync(message, sendCallback);
}
}
3、消费者配置类
import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
@Configuration
public class AliyunMqConsumerConfig {
@Value("${aliyun.mq.accessKey}")
private String accessKey;
@Value("${aliyun.mq.secretKey}")
private String secretKey;
@Value("${aliyun.mq.namesrvAddr}")
private String namesrvAddr;
@Bean(name = "consumer1", initMethod = "start", destroyMethod = "shutdown")
public Consumer consumer1() {
Properties properties = new Properties();
// 您在 MQ 控制台创建的 groupID
properties.put(PropertyKeyConst.GROUP_ID, "gid1");
// 鉴权用 AccessKey,在阿里云服务器管理控制台创建
properties.put(PropertyKeyConst.AccessKey, accessKey);
// 鉴权用 SecretKey,在阿里云服务器管理控制台创建
properties.put(PropertyKeyConst.SecretKey, secretKey);
// 设置 TCP 接入域名(此处以公共云公网环境接入为例)
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
// 设置发送超时时间,单位毫秒
properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
Consumer consumer = ONSFactory.createConsumer(properties);
return consumer;
}
@Bean(name = "consumer2", initMethod = "start", destroyMethod = "shutdown")
public Consumer consumer2() {
Properties properties = new Properties();
// 您在 MQ 控制台创建的 groupID
properties.put(PropertyKeyConst.GROUP_ID, "gid2");
// 鉴权用 AccessKey,在阿里云服务器管理控制台创建
properties.put(PropertyKeyConst.AccessKey, accessKey);
// 鉴权用 SecretKey,在阿里云服务器管理控制台创建
properties.put(PropertyKeyConst.SecretKey, secretKey);
// 设置 TCP 接入域名(此处以公共云公网环境接入为例)
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
// 设置发送超时时间,单位毫秒
properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
Consumer consumer = ONSFactory.createConsumer(properties);
return consumer;
}
}
4、消费者监听类
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
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;
@Component
public class AliyunMqListener implements ApplicationRunner {
@Resource(name = "consumer1")
private Consumer consumer1;
@Resource(name = "consumer2")
private Consumer consumer2;
@Value("${aliyun.mq.topic1}")
private String topic1;
@Value("${aliyun.mq.topic2}")
private String topic2;
@Autowired
private AliyunMqMessageListener1 aliyunMqMessageListener1;
@Autowired
private AliyunMqMessageListener2 aliyunMqMessageListener2;
private static final Logger logger = LoggerFactory.getLogger(AliyunMqListener.class);
@Override
public void run(ApplicationArguments args) throws Exception {
consumer1.subscribe(topic1, "*", aliyunMqMessageListener1); // 初始化监听目标
consumer1.start();
consumer2.subscribe(topic2, "*", aliyunMqMessageListener2); // 初始化监听目标
consumer2.start();
}
@Component
public class AliyunMqMessageListener1 implements MessageListener {
@Override
public Action consume(Message message, ConsumeContext context) {
logger.info("Receive:{}", message);
System.out.println(message);
return Action.CommitMessage;
}
}
@Component
public class AliyunMqMessageListener2 implements MessageListener {
@Override
public Action consume(Message message, ConsumeContext context) {
logger.info("Receive2:{}", message);
System.out.println(message);
return Action.CommitMessage;
}
}
}
5、发送消息测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.xx.application.BootApplication;
import com.xx.xx.rocketmq.AliyunMqProducer;
@RunWith(SpringJUnit4ClassRunner.class)
// 使用junit4进行测试
@ContextConfiguration(classes = BootApplication.class, loader = AnnotationConfigWebContextLoader.class)
// 加载配置文件
@WebAppConfiguration()
public class TestRocketMq {
@Autowired
private AliyunMqProducer aliyunMqProducer;
@Test
public void productTest() {
String topic = "topic1";
String key = "000103";
byte[] body = "sdsss".getBytes();
SendResult sendResult = aliyunMqProducer.send(topic, key, body);
System.out.println(JSONObject.toJSONString(sendResult));
String topic2 = "topic2";
String key2 = "000104";
byte[] body2 = "xxxxxxxxxxxxxxx".getBytes();
SendResult sendResult2 = aliyunMqProducer.send(topic2, key2, body2);
System.out.println(JSONObject.toJSONString(sendResult2));
}
}