1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

sync rocketmq binder to 1.x

This commit is contained in:
fangjian0423 2019-02-28 16:39:22 +08:00
parent 348f699eb8
commit 97ddae22fc
22 changed files with 473 additions and 138 deletions

View File

@ -31,7 +31,8 @@
<module>fescar-example/storage-service</module> <module>fescar-example/storage-service</module>
<module>fescar-example/account-service</module> <module>fescar-example/account-service</module>
<module>acm-example/acm-local-example</module> <module>acm-example/acm-local-example</module>
<module>rocketmq-example</module> <module>rocketmq-example/rocketmq-consume-example</module>
<module>rocketmq-example/rocketmq-produce-example</module>
<module>env-extension</module> <module>env-extension</module>
<module>sms-example</module> <module>sms-example</module>
<module>spring-cloud-bus-rocketmq-example</module> <module>spring-cloud-bus-rocketmq-example</module>

View File

@ -6,13 +6,14 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId> <artifactId>spring-cloud-alibaba-examples</artifactId>
<version>0.1.2.BUILD-SNAPSHOT</version> <version>0.1.2.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>rocketmq-example</artifactId> <artifactId>rocketmq-consume-example</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<description>Example demonstrating how to use rocketmq</description> <description>Example demonstrating how to use rocketmq consume</description>
<dependencies> <dependencies>
@ -20,14 +21,17 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId> <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
@ -48,4 +52,3 @@
</build> </build>
</project> </project>

View File

@ -0,0 +1,36 @@
package org.springframework.cloud.alibaba.cloud.examples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.alibaba.cloud.examples.RocketMQConsumerApplication.MySink;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@SpringBootApplication
@EnableBinding({ MySink.class })
public class RocketMQConsumerApplication {
public interface MySink {
@Input("input1")
SubscribableChannel input1();
@Input("input2")
SubscribableChannel input2();
@Input("input3")
SubscribableChannel input3();
@Input("input4")
SubscribableChannel input4();
}
public static void main(String[] args) {
SpringApplication.run(RocketMQConsumerApplication.class, args);
}
}

View File

@ -1,39 +1,32 @@
spring.cloud.stream.default-binder=rocketmq spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
spring.cloud.stream.rocketmq.binder.namesrv-addr=127.0.0.1:9876
spring.cloud.stream.bindings.output1.destination=test-topic
spring.cloud.stream.bindings.output1.content-type=application/json
spring.cloud.stream.bindings.output2.destination=TransactionTopic
spring.cloud.stream.bindings.output2.content-type=application/json
spring.cloud.stream.rocketmq.bindings.output2.producer.transactional=true
spring.cloud.stream.bindings.input1.destination=test-topic spring.cloud.stream.bindings.input1.destination=test-topic
spring.cloud.stream.bindings.input1.content-type=text/plain spring.cloud.stream.bindings.input1.content-type=text/plain
spring.cloud.stream.bindings.input1.group=test-group1 spring.cloud.stream.bindings.input1.group=test-group1
spring.cloud.stream.rocketmq.bindings.input1.consumer.orderly=true spring.cloud.stream.rocketmq.bindings.input1.consumer.orderly=true
spring.cloud.stream.bindings.input1.consumer.maxAttempts=1
spring.cloud.stream.bindings.input2.destination=test-topic spring.cloud.stream.bindings.input2.destination=test-topic
spring.cloud.stream.bindings.input2.content-type=text/plain spring.cloud.stream.bindings.input2.content-type=text/plain
spring.cloud.stream.bindings.input2.group=test-group2 spring.cloud.stream.bindings.input2.group=test-group2
spring.cloud.stream.rocketmq.bindings.input2.consumer.orderly=false spring.cloud.stream.rocketmq.bindings.input2.consumer.orderly=false
spring.cloud.stream.rocketmq.bindings.input2.consumer.tags=tagStr spring.cloud.stream.rocketmq.bindings.input2.consumer.tags=tagStr
spring.cloud.stream.bindings.input2.consumer.concurrency=5 spring.cloud.stream.bindings.input2.consumer.concurrency=20
spring.cloud.stream.bindings.input2.consumer.maxAttempts=1
spring.cloud.stream.bindings.input3.destination=test-topic spring.cloud.stream.bindings.input3.destination=test-topic
spring.cloud.stream.bindings.input3.content-type=application/json spring.cloud.stream.bindings.input3.content-type=application/json
spring.cloud.stream.bindings.input3.group=test-group3 spring.cloud.stream.bindings.input3.group=test-group3
spring.cloud.stream.rocketmq.bindings.input3.consumer.tags=tagObj spring.cloud.stream.rocketmq.bindings.input3.consumer.tags=tagObj
spring.cloud.stream.bindings.input3.consumer.concurrency=5 spring.cloud.stream.bindings.input3.consumer.concurrency=20
spring.cloud.stream.bindings.input4.destination=TransactionTopic spring.cloud.stream.bindings.input4.destination=TransactionTopic
spring.cloud.stream.bindings.input4.content-type=text/plain spring.cloud.stream.bindings.input4.content-type=text/plain
spring.cloud.stream.bindings.input4.group=transaction-group spring.cloud.stream.bindings.input4.group=transaction-group
spring.cloud.stream.bindings.input4.consumer.concurrency=10 spring.cloud.stream.bindings.input4.consumer.concurrency=5
spring.application.name=rocketmq-example spring.application.name=rocketmq-consume-example
server.port=28081 server.port=28082
management.security.enabled=false
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>0.1.2.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>rocketmq-produce-example</artifactId>
<packaging>jar</packaging>
<description>Example demonstrating how to use rocketmq produce</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,39 @@
package org.springframework.cloud.alibaba.cloud.examples;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class Foo {
private int id;
private String bar;
public Foo() {
}
public Foo(int id, String bar) {
this.id = id;
this.bar = bar;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
@Override
public String toString() {
return "Foo{" + "id=" + id + ", bar='" + bar + '\'' + '}';
}
}

View File

@ -4,37 +4,18 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.alibaba.cloud.examples.RocketMQApplication.MySink; import org.springframework.cloud.alibaba.cloud.examples.RocketMQProduceApplication.MySource;
import org.springframework.cloud.alibaba.cloud.examples.RocketMQApplication.MySource;
import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output; import org.springframework.cloud.stream.annotation.Output;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
/** /**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a> * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/ */
@SpringBootApplication @SpringBootApplication
@EnableBinding({ MySource.class, MySink.class }) @EnableBinding({ MySource.class })
public class RocketMQApplication { public class RocketMQProduceApplication {
public interface MySink {
@Input("input1")
SubscribableChannel input1();
@Input("input2")
SubscribableChannel input2();
@Input("input3")
SubscribableChannel input3();
@Input("input4")
SubscribableChannel input4();
}
public interface MySource { public interface MySource {
@Output("output1") @Output("output1")
@ -45,7 +26,7 @@ public class RocketMQApplication {
} }
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(RocketMQApplication.class, args); SpringApplication.run(RocketMQProduceApplication.class, args);
} }
@Bean @Bean
@ -87,13 +68,13 @@ public class RocketMQApplication {
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
// COMMIT_MESSAGE message // COMMIT_MESSAGE message
senderService.sendTransactionalMsg("transactional-msg1", false); senderService.sendTransactionalMsg("transactional-msg1", 1);
// ROLLBACK_MESSAGE message // ROLLBACK_MESSAGE message
senderService.sendTransactionalMsg("transactional-msg2", true); senderService.sendTransactionalMsg("transactional-msg2", 2);
// ROLLBACK_MESSAGE message // ROLLBACK_MESSAGE message
senderService.sendTransactionalMsg("transactional-msg3", true); senderService.sendTransactionalMsg("transactional-msg3", 3);
// COMMIT_MESSAGE message // COMMIT_MESSAGE message
senderService.sendTransactionalMsg("transactional-msg4", false); senderService.sendTransactionalMsg("transactional-msg4", 4);
} }
} }

View File

@ -2,10 +2,13 @@ package org.springframework.cloud.alibaba.cloud.examples;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.cloud.examples.RocketMQApplication.MySource; import org.springframework.cloud.alibaba.cloud.examples.RocketMQProduceApplication.MySource;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageBuilder;
@ -40,12 +43,11 @@ public class SenderService {
source.output1().send(message); source.output1().send(message);
} }
public <T> void sendTransactionalMsg(T msg, boolean error) throws Exception { public <T> void sendTransactionalMsg(T msg, int num) throws Exception {
MessageBuilder builder = MessageBuilder.withPayload(msg) MessageBuilder builder = MessageBuilder.withPayload(msg)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON); .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
if (error) { builder.setHeader("test", String.valueOf(num));
builder.setHeader("test", "1"); builder.setHeader(RocketMQHeaders.TAGS, "binder");
}
Message message = builder.build(); Message message = builder.build();
source.output2().send(message); source.output2().send(message);
} }

View File

@ -27,13 +27,20 @@ import org.springframework.messaging.Message;
/** /**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a> * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/ */
@RocketMQTransactionListener(txProducerGroup = "TransactionTopic", corePoolSize = 5, maximumPoolSize = 10) @RocketMQTransactionListener(txProducerGroup = "myTxProducerGroup", corePoolSize = 5, maximumPoolSize = 10)
class TransactionListenerImpl implements RocketMQLocalTransactionListener { public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
@Override @Override
public RocketMQLocalTransactionState executeLocalTransaction(Message msg, public RocketMQLocalTransactionState executeLocalTransaction(Message msg,
Object arg) { Object arg) {
if ("1".equals(((HashMap) msg.getHeaders().get(RocketMQHeaders.PROPERTIES)) Object num = ((HashMap) msg.getHeaders().get(RocketMQHeaders.PROPERTIES))
.get("USERS_test"))) { .get("USERS_test");
if ("1".equals(num)) {
System.out.println(
"executer: " + new String((byte[]) msg.getPayload()) + " unknown");
return RocketMQLocalTransactionState.UNKNOWN;
}
else if ("2".equals(num)) {
System.out.println( System.out.println(
"executer: " + new String((byte[]) msg.getPayload()) + " rollback"); "executer: " + new String((byte[]) msg.getPayload()) + " rollback");
return RocketMQLocalTransactionState.ROLLBACK; return RocketMQLocalTransactionState.ROLLBACK;

View File

@ -0,0 +1,20 @@
logging.level.org.springframework.cloud.stream.binder.rocketmq=DEBUG
spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
spring.cloud.stream.bindings.output1.destination=test-topic
spring.cloud.stream.bindings.output1.content-type=application/json
spring.cloud.stream.rocketmq.bindings.output1.producer.group=binder-group
spring.cloud.stream.rocketmq.bindings.output1.producer.sync=true
spring.cloud.stream.bindings.output2.destination=TransactionTopic
spring.cloud.stream.bindings.output2.content-type=application/json
spring.cloud.stream.rocketmq.bindings.output2.producer.transactional=true
spring.cloud.stream.rocketmq.bindings.output2.producer.group=myTxProducerGroup
spring.application.name=rocketmq-produce-example
server.port=28081
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -0,0 +1,72 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.binder.rocketmq;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.springframework.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties;
import org.springframework.util.StringUtils;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class RocketMQBinderUtils {
public static RocketMQBinderConfigurationProperties mergeProducerProperties(
RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties,
RocketMQProperties rocketMQProperties) {
RocketMQBinderConfigurationProperties result = new RocketMQBinderConfigurationProperties();
if (StringUtils.isEmpty(rocketMQProperties.getNameServer())) {
result.setNameServer(rocketBinderConfigurationProperties.getNameServer());
}
else {
result.setNameServer(rocketMQProperties.getNameServer());
}
if (rocketMQProperties.getProducer() == null
|| StringUtils.isEmpty(rocketMQProperties.getProducer().getAccessKey())) {
result.setAccessKey(rocketBinderConfigurationProperties.getAccessKey());
}
else {
result.setAccessKey(rocketMQProperties.getProducer().getAccessKey());
}
if (rocketMQProperties.getProducer() == null
|| StringUtils.isEmpty(rocketMQProperties.getProducer().getSecretKey())) {
result.setSecretKey(rocketBinderConfigurationProperties.getSecretKey());
}
else {
result.setSecretKey(rocketMQProperties.getProducer().getSecretKey());
}
if (rocketMQProperties.getProducer() == null || StringUtils
.isEmpty(rocketMQProperties.getProducer().getCustomizedTraceTopic())) {
result.setCustomizedTraceTopic(
rocketBinderConfigurationProperties.getCustomizedTraceTopic());
}
else {
result.setCustomizedTraceTopic(
rocketMQProperties.getProducer().getCustomizedTraceTopic());
}
if (rocketMQProperties.getProducer() != null
&& rocketMQProperties.getProducer().isEnableMsgTrace()) {
result.setEnableMsgTrace(Boolean.TRUE);
}
else {
result.setEnableMsgTrace(
rocketBinderConfigurationProperties.isEnableMsgTrace());
}
return result;
}
}

View File

@ -21,8 +21,13 @@ import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.springframework.cloud.stream.binder.AbstractMessageChannelBinder; import org.springframework.cloud.stream.binder.AbstractMessageChannelBinder;
import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties;
import org.springframework.cloud.stream.binder.ExtendedProducerProperties; import org.springframework.cloud.stream.binder.ExtendedProducerProperties;
@ -41,6 +46,7 @@ import org.springframework.cloud.stream.provisioning.ProducerDestination;
import org.springframework.integration.core.MessageProducer; import org.springframework.integration.core.MessageProducer;
import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessageHandler;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -54,6 +60,7 @@ public class RocketMQMessageChannelBinder extends
private final RocketMQExtendedBindingProperties extendedBindingProperties; private final RocketMQExtendedBindingProperties extendedBindingProperties;
private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties; private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties;
private final RocketMQProperties rocketMQProperties;
private final InstrumentationManager instrumentationManager; private final InstrumentationManager instrumentationManager;
private Set<String> clientConfigId = new HashSet<>(); private Set<String> clientConfigId = new HashSet<>();
@ -63,9 +70,11 @@ public class RocketMQMessageChannelBinder extends
RocketMQExtendedBindingProperties extendedBindingProperties, RocketMQExtendedBindingProperties extendedBindingProperties,
RocketMQTopicProvisioner provisioningProvider, RocketMQTopicProvisioner provisioningProvider,
RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties, RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties,
RocketMQProperties rocketMQProperties,
InstrumentationManager instrumentationManager) { InstrumentationManager instrumentationManager) {
super(true, null, provisioningProvider); super(true, null, provisioningProvider);
this.extendedBindingProperties = extendedBindingProperties; this.extendedBindingProperties = extendedBindingProperties;
this.rocketMQProperties = rocketMQProperties;
this.rocketBinderConfigurationProperties = rocketBinderConfigurationProperties; this.rocketBinderConfigurationProperties = rocketBinderConfigurationProperties;
this.instrumentationManager = instrumentationManager; this.instrumentationManager = instrumentationManager;
} }
@ -76,6 +85,10 @@ public class RocketMQMessageChannelBinder extends
MessageChannel errorChannel) throws Exception { MessageChannel errorChannel) throws Exception {
if (producerProperties.getExtension().getEnabled()) { if (producerProperties.getExtension().getEnabled()) {
RocketMQBinderConfigurationProperties mergedProperties = RocketMQBinderUtils
.mergeProducerProperties(rocketBinderConfigurationProperties,
rocketMQProperties);
RocketMQTemplate rocketMQTemplate; RocketMQTemplate rocketMQTemplate;
if (producerProperties.getExtension().getTransactional()) { if (producerProperties.getExtension().getTransactional()) {
Map<String, RocketMQTemplate> rocketMQTemplates = getApplicationContext() Map<String, RocketMQTemplate> rocketMQTemplates = getApplicationContext()
@ -95,9 +108,27 @@ public class RocketMQMessageChannelBinder extends
rocketMQTemplate = new RocketMQTemplate(); rocketMQTemplate = new RocketMQTemplate();
rocketMQTemplate.setObjectMapper(getApplicationContext().getParent() rocketMQTemplate.setObjectMapper(getApplicationContext().getParent()
.getBeansOfType(ObjectMapper.class).values().iterator().next()); .getBeansOfType(ObjectMapper.class).values().iterator().next());
DefaultMQProducer producer = new DefaultMQProducer(destination.getName()); DefaultMQProducer producer;
producer.setNamesrvAddr( String ak = mergedProperties.getAccessKey();
rocketBinderConfigurationProperties.getNamesrvAddr()); String sk = mergedProperties.getSecretKey();
if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) {
RPCHook rpcHook = new AclClientRPCHook(
new SessionCredentials(ak, sk));
producer = new DefaultMQProducer(
producerProperties.getExtension().getGroup(), rpcHook,
mergedProperties.isEnableMsgTrace(),
mergedProperties.getCustomizedTraceTopic());
producer.setVipChannelEnabled(false);
producer.setInstanceName(
RocketMQUtil.getInstanceName(rpcHook, destination.getName()));
}
else {
producer = new DefaultMQProducer(
producerProperties.getExtension().getGroup());
producer.setVipChannelEnabled(
producerProperties.getExtension().getVipChannelEnabled());
}
producer.setNamesrvAddr(mergedProperties.getNameServer());
producer.setSendMsgTimeout( producer.setSendMsgTimeout(
producerProperties.getExtension().getSendMessageTimeout()); producerProperties.getExtension().getSendMessageTimeout());
producer.setRetryTimesWhenSendFailed( producer.setRetryTimesWhenSendFailed(
@ -110,14 +141,13 @@ public class RocketMQMessageChannelBinder extends
producerProperties.getExtension().isRetryNextServer()); producerProperties.getExtension().isRetryNextServer());
producer.setMaxMessageSize( producer.setMaxMessageSize(
producerProperties.getExtension().getMaxMessageSize()); producerProperties.getExtension().getMaxMessageSize());
producer.setVipChannelEnabled(
producerProperties.getExtension().getVipChannelEnabled());
rocketMQTemplate.setProducer(producer); rocketMQTemplate.setProducer(producer);
clientConfigId.add(producer.buildMQClientId()); clientConfigId.add(producer.buildMQClientId());
} }
RocketMQMessageHandler messageHandler = new RocketMQMessageHandler( RocketMQMessageHandler messageHandler = new RocketMQMessageHandler(
rocketMQTemplate, destination.getName(), rocketMQTemplate, destination.getName(),
producerProperties.getExtension().getGroup(),
producerProperties.getExtension().getTransactional(), producerProperties.getExtension().getTransactional(),
instrumentationManager); instrumentationManager);
messageHandler.setBeanFactory(this.getApplicationContext().getBeanFactory()); messageHandler.setBeanFactory(this.getApplicationContext().getBeanFactory());
@ -145,7 +175,7 @@ public class RocketMQMessageChannelBinder extends
} }
RocketMQListenerBindingContainer listenerContainer = new RocketMQListenerBindingContainer( RocketMQListenerBindingContainer listenerContainer = new RocketMQListenerBindingContainer(
consumerProperties, this); consumerProperties, rocketBinderConfigurationProperties, this);
listenerContainer.setConsumerGroup(group); listenerContainer.setConsumerGroup(group);
listenerContainer.setTopic(destination.getName()); listenerContainer.setTopic(destination.getName());
listenerContainer.setConsumeThreadMax(consumerProperties.getConcurrency()); listenerContainer.setConsumeThreadMax(consumerProperties.getConcurrency());
@ -154,7 +184,7 @@ public class RocketMQMessageChannelBinder extends
listenerContainer.setDelayLevelWhenNextConsume( listenerContainer.setDelayLevelWhenNextConsume(
consumerProperties.getExtension().getDelayLevelWhenNextConsume()); consumerProperties.getExtension().getDelayLevelWhenNextConsume());
listenerContainer listenerContainer
.setNameServer(rocketBinderConfigurationProperties.getNamesrvAddr()); .setNameServer(rocketBinderConfigurationProperties.getNameServer());
RocketMQInboundChannelAdapter rocketInboundChannelAdapter = new RocketMQInboundChannelAdapter( RocketMQInboundChannelAdapter rocketInboundChannelAdapter = new RocketMQInboundChannelAdapter(
listenerContainer, consumerProperties, instrumentationManager); listenerContainer, consumerProperties, instrumentationManager);

View File

@ -16,6 +16,8 @@
package org.springframework.cloud.stream.binder.rocketmq.config; package org.springframework.cloud.stream.binder.rocketmq.config;
import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.stream.binder.rocketmq.RocketMQMessageChannelBinder; import org.springframework.cloud.stream.binder.rocketmq.RocketMQMessageChannelBinder;
@ -32,7 +34,8 @@ import org.springframework.context.annotation.Import;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a> * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/ */
@Configuration @Configuration
@Import(RocketMQBinderHealthIndicatorAutoConfiguration.class) @Import({ RocketMQAutoConfiguration.class,
RocketMQBinderHealthIndicatorAutoConfiguration.class })
@EnableConfigurationProperties({ RocketMQBinderConfigurationProperties.class, @EnableConfigurationProperties({ RocketMQBinderConfigurationProperties.class,
RocketMQExtendedBindingProperties.class }) RocketMQExtendedBindingProperties.class })
public class RocketMQBinderAutoConfiguration { public class RocketMQBinderAutoConfiguration {
@ -41,6 +44,9 @@ public class RocketMQBinderAutoConfiguration {
private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties; private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties;
@Autowired(required = false)
private RocketMQProperties rocketMQProperties = new RocketMQProperties();
@Autowired @Autowired
public RocketMQBinderAutoConfiguration( public RocketMQBinderAutoConfiguration(
RocketMQExtendedBindingProperties extendedBindingProperties, RocketMQExtendedBindingProperties extendedBindingProperties,
@ -60,7 +66,8 @@ public class RocketMQBinderAutoConfiguration {
InstrumentationManager instrumentationManager) { InstrumentationManager instrumentationManager) {
RocketMQMessageChannelBinder binder = new RocketMQMessageChannelBinder( RocketMQMessageChannelBinder binder = new RocketMQMessageChannelBinder(
extendedBindingProperties, provisioningProvider, extendedBindingProperties, provisioningProvider,
rocketBinderConfigurationProperties, instrumentationManager); rocketBinderConfigurationProperties, rocketMQProperties,
instrumentationManager);
return binder; return binder;
} }

View File

@ -16,11 +16,10 @@
package org.springframework.cloud.stream.binder.rocketmq.config; package org.springframework.cloud.stream.binder.rocketmq.config;
import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration; import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties.Producer;
import org.apache.rocketmq.spring.config.RocketMQConfigUtils; import org.apache.rocketmq.spring.config.RocketMQConfigUtils;
import org.apache.rocketmq.spring.config.RocketMQTransactionAnnotationProcessor; import org.apache.rocketmq.spring.config.RocketMQTransactionAnnotationProcessor;
import org.apache.rocketmq.spring.config.TransactionHandlerRegistry; import org.apache.rocketmq.spring.config.TransactionHandlerRegistry;
@ -32,7 +31,6 @@ import org.springframework.cloud.stream.binder.rocketmq.RocketMQBinderConstants;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.util.Assert;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -51,48 +49,35 @@ public class RocketMQComponent4BinderAutoConfiguration {
} }
@Bean @Bean
@ConditionalOnMissingBean(DefaultMQProducer.class)
public DefaultMQProducer defaultMQProducer() { public DefaultMQProducer defaultMQProducer() {
RocketMQProperties rocketMQProperties = new RocketMQProperties(); DefaultMQProducer producer;
String configNameServer = environment String configNameServer = environment.resolveRequiredPlaceholders(
.getProperty("spring.cloud.stream.rocketmq.binder.namesrv-addr"); "${spring.cloud.stream.rocketmq.binder.name-server:${rocketmq.producer.name-server:}}");
if (StringUtils.isEmpty(configNameServer)) { String ak = environment.resolveRequiredPlaceholders(
rocketMQProperties.setNameServer(RocketMQBinderConstants.DEFAULT_NAME_SERVER); "${spring.cloud.stream.rocketmq.binder.access-key:${rocketmq.producer.access-key:}}");
String sk = environment.resolveRequiredPlaceholders(
"${spring.cloud.stream.rocketmq.binder.secret-key:${rocketmq.producer.secret-key:}}");
if (!org.springframework.util.StringUtils.isEmpty(ak)
&& !org.springframework.util.StringUtils.isEmpty(sk)) {
producer = new DefaultMQProducer(RocketMQBinderConstants.DEFAULT_GROUP,
new AclClientRPCHook(new SessionCredentials(ak, sk)));
producer.setVipChannelEnabled(false);
} }
else { else {
rocketMQProperties.setNameServer(configNameServer); producer = new DefaultMQProducer(RocketMQBinderConstants.DEFAULT_GROUP);
} }
RocketMQProperties.Producer producerConfig = new Producer(); producer.setNamesrvAddr(configNameServer);
rocketMQProperties.setProducer(producerConfig);
producerConfig.setGroup(RocketMQBinderConstants.DEFAULT_GROUP);
String nameServer = rocketMQProperties.getNameServer();
String groupName = producerConfig.getGroup();
Assert.hasText(nameServer, "[rocketmq.name-server] must not be null");
Assert.hasText(groupName, "[rocketmq.producer.group] must not be null");
DefaultMQProducer producer = new DefaultMQProducer(groupName);
producer.setNamesrvAddr(nameServer);
producer.setSendMsgTimeout(producerConfig.getSendMessageTimeout());
producer.setRetryTimesWhenSendFailed(
producerConfig.getRetryTimesWhenSendFailed());
producer.setRetryTimesWhenSendAsyncFailed(
producerConfig.getRetryTimesWhenSendAsyncFailed());
producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
producer.setCompressMsgBodyOverHowmuch(
producerConfig.getCompressMessageBodyThreshold());
producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryNextServer());
return producer; return producer;
} }
@Bean(destroyMethod = "destroy") @Bean(destroyMethod = "destroy")
@ConditionalOnBean(DefaultMQProducer.class) @ConditionalOnMissingBean
@ConditionalOnMissingBean(RocketMQTemplate.class)
public RocketMQTemplate rocketMQTemplate(DefaultMQProducer mqProducer, public RocketMQTemplate rocketMQTemplate(DefaultMQProducer mqProducer,
ObjectMapper rocketMQMessageObjectMapper) { ObjectMapper objectMapper) {
RocketMQTemplate rocketMQTemplate = new RocketMQTemplate(); RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
rocketMQTemplate.setProducer(mqProducer); rocketMQTemplate.setProducer(mqProducer);
rocketMQTemplate.setObjectMapper(rocketMQMessageObjectMapper); rocketMQTemplate.setObjectMapper(objectMapper);
return rocketMQTemplate; return rocketMQTemplate;
} }

View File

@ -18,6 +18,8 @@ package org.springframework.cloud.stream.binder.rocketmq.consuming;
import java.util.List; import java.util.List;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector; import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
@ -26,8 +28,10 @@ import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus; import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly; import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.consumer.rebalance.AllocateMessageQueueAveragely;
import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.spring.annotation.ConsumeMode; import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel; import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.SelectorType; import org.apache.rocketmq.spring.annotation.SelectorType;
@ -40,6 +44,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties;
import org.springframework.cloud.stream.binder.rocketmq.RocketMQMessageChannelBinder; import org.springframework.cloud.stream.binder.rocketmq.RocketMQMessageChannelBinder;
import org.springframework.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties;
import org.springframework.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties; import org.springframework.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties;
import org.springframework.context.SmartLifecycle; import org.springframework.context.SmartLifecycle;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -83,6 +88,7 @@ public class RocketMQListenerBindingContainer
private final ExtendedConsumerProperties<RocketMQConsumerProperties> rocketMQConsumerProperties; private final ExtendedConsumerProperties<RocketMQConsumerProperties> rocketMQConsumerProperties;
private final RocketMQMessageChannelBinder rocketMQMessageChannelBinder; private final RocketMQMessageChannelBinder rocketMQMessageChannelBinder;
private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties;
// The following properties came from RocketMQConsumerProperties. // The following properties came from RocketMQConsumerProperties.
private ConsumeMode consumeMode; private ConsumeMode consumeMode;
@ -92,8 +98,10 @@ public class RocketMQListenerBindingContainer
public RocketMQListenerBindingContainer( public RocketMQListenerBindingContainer(
ExtendedConsumerProperties<RocketMQConsumerProperties> rocketMQConsumerProperties, ExtendedConsumerProperties<RocketMQConsumerProperties> rocketMQConsumerProperties,
RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties,
RocketMQMessageChannelBinder rocketMQMessageChannelBinder) { RocketMQMessageChannelBinder rocketMQMessageChannelBinder) {
this.rocketMQConsumerProperties = rocketMQConsumerProperties; this.rocketMQConsumerProperties = rocketMQConsumerProperties;
this.rocketBinderConfigurationProperties = rocketBinderConfigurationProperties;
this.rocketMQMessageChannelBinder = rocketMQMessageChannelBinder; this.rocketMQMessageChannelBinder = rocketMQMessageChannelBinder;
this.consumeMode = rocketMQConsumerProperties.getExtension().getOrderly() this.consumeMode = rocketMQConsumerProperties.getExtension().getOrderly()
? ConsumeMode.ORDERLY ? ConsumeMode.ORDERLY
@ -189,7 +197,23 @@ public class RocketMQListenerBindingContainer
Assert.notNull(nameServer, "Property 'nameServer' is required"); Assert.notNull(nameServer, "Property 'nameServer' is required");
Assert.notNull(topic, "Property 'topic' is required"); Assert.notNull(topic, "Property 'topic' is required");
consumer = new DefaultMQPushConsumer(consumerGroup); String ak = rocketBinderConfigurationProperties.getAccessKey();
String sk = rocketBinderConfigurationProperties.getSecretKey();
if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) {
RPCHook rpcHook = new AclClientRPCHook(new SessionCredentials(ak, sk));
consumer = new DefaultMQPushConsumer(consumerGroup, rpcHook,
new AllocateMessageQueueAveragely(),
rocketBinderConfigurationProperties.isEnableMsgTrace(),
rocketBinderConfigurationProperties.getCustomizedTraceTopic());
consumer.setInstanceName(RocketMQUtil.getInstanceName(rpcHook, topic));
consumer.setVipChannelEnabled(false);
}
else {
consumer = new DefaultMQPushConsumer(consumerGroup,
rocketBinderConfigurationProperties.isEnableMsgTrace(),
rocketBinderConfigurationProperties.getCustomizedTraceTopic());
}
consumer.setNamesrvAddr(nameServer); consumer.setNamesrvAddr(nameServer);
consumer.setConsumeThreadMax(rocketMQConsumerProperties.getConcurrency()); consumer.setConsumeThreadMax(rocketMQConsumerProperties.getConcurrency());
consumer.setConsumeThreadMin(rocketMQConsumerProperties.getConcurrency()); consumer.setConsumeThreadMin(rocketMQConsumerProperties.getConcurrency());
@ -238,6 +262,15 @@ public class RocketMQListenerBindingContainer
} }
@Override
public String toString() {
return "RocketMQListenerBindingContainer{" + "consumerGroup='" + consumerGroup
+ '\'' + ", nameServer='" + nameServer + '\'' + ", topic='" + topic + '\''
+ ", consumeMode=" + consumeMode + ", selectorType=" + selectorType
+ ", selectorExpression='" + selectorExpression + '\'' + ", messageModel="
+ messageModel + '}';
}
public long getSuspendCurrentQueueTimeMillis() { public long getSuspendCurrentQueueTimeMillis() {
return suspendCurrentQueueTimeMillis; return suspendCurrentQueueTimeMillis;
} }

View File

@ -40,7 +40,7 @@ import org.springframework.util.Assert;
*/ */
public class RocketMQInboundChannelAdapter extends MessageProducerSupport { public class RocketMQInboundChannelAdapter extends MessageProducerSupport {
private static final Logger logger = LoggerFactory private static final Logger log = LoggerFactory
.getLogger(RocketMQInboundChannelAdapter.class); .getLogger(RocketMQInboundChannelAdapter.class);
private RetryTemplate retryTemplate; private RetryTemplate retryTemplate;
@ -88,7 +88,7 @@ public class RocketMQInboundChannelAdapter extends MessageProducerSupport {
} }
catch (Exception e) { catch (Exception e) {
logger.error("rocketMQListenerContainer init error: " + e.getMessage(), e); log.error("rocketMQListenerContainer init error: " + e.getMessage(), e);
throw new IllegalArgumentException( throw new IllegalArgumentException(
"rocketMQListenerContainer init error: " + e.getMessage(), e); "rocketMQListenerContainer init error: " + e.getMessage(), e);
} }
@ -116,7 +116,7 @@ public class RocketMQInboundChannelAdapter extends MessageProducerSupport {
.getHealthInstrumentation(rocketMQListenerContainer.getTopic() .getHealthInstrumentation(rocketMQListenerContainer.getTopic()
+ rocketMQListenerContainer.getConsumerGroup()) + rocketMQListenerContainer.getConsumerGroup())
.markStartFailed(e); .markStartFailed(e);
logger.error("RocketMQTemplate startup failed, Caused by " + e.getMessage()); log.error("RocketMQTemplate startup failed, Caused by " + e.getMessage());
throw new MessagingException(MessageBuilder.withPayload( throw new MessagingException(MessageBuilder.withPayload(
"RocketMQTemplate startup failed, Caused by " + e.getMessage()) "RocketMQTemplate startup failed, Caused by " + e.getMessage())
.build(), e); .build(), e);

View File

@ -23,6 +23,8 @@ import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders; import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.binder.rocketmq.RocketMQBinderConstants; import org.springframework.cloud.stream.binder.rocketmq.RocketMQBinderConstants;
import org.springframework.cloud.stream.binder.rocketmq.metrics.Instrumentation; import org.springframework.cloud.stream.binder.rocketmq.metrics.Instrumentation;
import org.springframework.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; import org.springframework.cloud.stream.binder.rocketmq.metrics.InstrumentationManager;
@ -42,6 +44,9 @@ import org.springframework.util.StringUtils;
*/ */
public class RocketMQMessageHandler extends AbstractMessageHandler implements Lifecycle { public class RocketMQMessageHandler extends AbstractMessageHandler implements Lifecycle {
private final static Logger log = LoggerFactory
.getLogger(RocketMQMessageHandler.class);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy(); private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private MessageChannel sendFailureChannel; private MessageChannel sendFailureChannel;
@ -52,6 +57,8 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li
private final String destination; private final String destination;
private final String groupName;
private final InstrumentationManager instrumentationManager; private final InstrumentationManager instrumentationManager;
private boolean sync = false; private boolean sync = false;
@ -59,9 +66,11 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li
private volatile boolean running = false; private volatile boolean running = false;
public RocketMQMessageHandler(RocketMQTemplate rocketMQTemplate, String destination, public RocketMQMessageHandler(RocketMQTemplate rocketMQTemplate, String destination,
Boolean transactional, InstrumentationManager instrumentationManager) { String group, Boolean transactional,
InstrumentationManager instrumentationManager) {
this.rocketMQTemplate = rocketMQTemplate; this.rocketMQTemplate = rocketMQTemplate;
this.destination = destination; this.destination = destination;
this.groupName = group;
this.transactional = transactional; this.transactional = transactional;
this.instrumentationManager = instrumentationManager; this.instrumentationManager = instrumentationManager;
} }
@ -79,8 +88,7 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li
catch (Exception e) { catch (Exception e) {
instrumentationManager.getHealthInstrumentation(destination) instrumentationManager.getHealthInstrumentation(destination)
.markStartFailed(e); .markStartFailed(e);
logger.error( log.error("RocketMQTemplate startup failed, Caused by " + e.getMessage());
"RocketMQTemplate startup failed, Caused by " + e.getMessage());
throw new MessagingException(MessageBuilder.withPayload( throw new MessagingException(MessageBuilder.withPayload(
"RocketMQTemplate startup failed, Caused by " + e.getMessage()) "RocketMQTemplate startup failed, Caused by " + e.getMessage())
.build(), e); .build(), e);
@ -106,19 +114,20 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li
protected void handleMessageInternal( protected void handleMessageInternal(
final org.springframework.messaging.Message<?> message) throws Exception { final org.springframework.messaging.Message<?> message) throws Exception {
try { try {
StringBuilder topicWithTags = new StringBuilder(destination); final StringBuilder topicWithTags = new StringBuilder(destination);
String tags = null; String tags = null;
if (message.getHeaders().get(RocketMQHeaders.TAGS) != null) { if (message.getHeaders().get(RocketMQHeaders.TAGS) != null) {
tags = message.getHeaders().get(RocketMQHeaders.TAGS).toString(); tags = message.getHeaders().get(RocketMQHeaders.TAGS).toString();
} }
if (!StringUtils.isEmpty(tags)) { if (!StringUtils.isEmpty(tags)) {
topicWithTags = topicWithTags.append(":").append(tags); topicWithTags.append(":").append(tags);
} }
SendResult sendRes = null; SendResult sendRes = null;
if (transactional) { if (transactional) {
sendRes = rocketMQTemplate.sendMessageInTransaction(destination, sendRes = rocketMQTemplate.sendMessageInTransaction(groupName,
topicWithTags.toString(), message, message.getHeaders() topicWithTags.toString(), message, message.getHeaders()
.get(RocketMQBinderConstants.ROCKET_TRANSACTIONAL_ARG)); .get(RocketMQBinderConstants.ROCKET_TRANSACTIONAL_ARG));
log.debug("transactional send to topic " + topicWithTags + " " + sendRes);
} }
else { else {
int delayLevel = 0; int delayLevel = 0;
@ -139,17 +148,22 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li
sendRes = rocketMQTemplate.syncSend(topicWithTags.toString(), message, sendRes = rocketMQTemplate.syncSend(topicWithTags.toString(), message,
rocketMQTemplate.getProducer().getSendMsgTimeout(), rocketMQTemplate.getProducer().getSendMsgTimeout(),
delayLevel); delayLevel);
log.debug("sync send to topic " + topicWithTags + " " + sendRes);
} }
else { else {
rocketMQTemplate.asyncSend(topicWithTags.toString(), message, rocketMQTemplate.asyncSend(topicWithTags.toString(), message,
new SendCallback() { new SendCallback() {
@Override @Override
public void onSuccess(SendResult sendResult) { public void onSuccess(SendResult sendResult) {
log.debug("async send to topic " + topicWithTags + " "
+ sendResult);
} }
@Override @Override
public void onException(Throwable e) { public void onException(Throwable e) {
log.error(
"RocketMQ Message hasn't been sent. Caused by "
+ e.getMessage());
if (getSendFailureChannel() != null) { if (getSendFailureChannel() != null) {
getSendFailureChannel().send( getSendFailureChannel().send(
RocketMQMessageHandler.this.errorMessageStrategy RocketMQMessageHandler.this.errorMessageStrategy
@ -173,8 +187,7 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li
} }
} }
catch (Exception e) { catch (Exception e) {
logger.error( log.error("RocketMQ Message hasn't been sent. Caused by " + e.getMessage());
"RocketMQ Message hasn't been sent. Caused by " + e.getMessage());
if (getSendFailureChannel() != null) { if (getSendFailureChannel() != null) {
getSendFailureChannel().send(this.errorMessageStrategy getSendFailureChannel().send(this.errorMessageStrategy
.buildErrorMessage(new MessagingException(message, e), null)); .buildErrorMessage(new MessagingException(message, e), null));

View File

@ -16,6 +16,7 @@
package org.springframework.cloud.stream.binder.rocketmq.properties; package org.springframework.cloud.stream.binder.rocketmq.properties;
import org.apache.rocketmq.common.MixAll;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.stream.binder.rocketmq.RocketMQBinderConstants; import org.springframework.cloud.stream.binder.rocketmq.RocketMQBinderConstants;
@ -26,24 +27,69 @@ import org.springframework.cloud.stream.binder.rocketmq.RocketMQBinderConstants;
@ConfigurationProperties(prefix = "spring.cloud.stream.rocketmq.binder") @ConfigurationProperties(prefix = "spring.cloud.stream.rocketmq.binder")
public class RocketMQBinderConfigurationProperties { public class RocketMQBinderConfigurationProperties {
private String namesrvAddr = RocketMQBinderConstants.DEFAULT_NAME_SERVER; /**
* The name server for rocketMQ, formats: `host:port;host:port`.
*/
private String nameServer = RocketMQBinderConstants.DEFAULT_NAME_SERVER;
private String logLevel = "ERROR"; /**
* The property of "access-key".
*/
private String accessKey;
public String getNamesrvAddr() { /**
return namesrvAddr; * The property of "secret-key".
*/
private String secretKey;
/**
* Switch flag instance for message trace.
*/
private boolean enableMsgTrace = true;
/**
* The name value of message trace topic.If you don't config,you can use the default
* trace topic name.
*/
private String customizedTraceTopic = MixAll.RMQ_SYS_TRACE_TOPIC;
public String getNameServer() {
return nameServer;
} }
public void setNamesrvAddr(String namesrvAddr) { public void setNameServer(String nameServer) {
this.namesrvAddr = namesrvAddr; this.nameServer = nameServer;
} }
public String getLogLevel() { public String getAccessKey() {
return logLevel; return accessKey;
} }
public void setLogLevel(String logLevel) { public void setAccessKey(String accessKey) {
this.logLevel = logLevel; this.accessKey = accessKey;
} }
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public boolean isEnableMsgTrace() {
return enableMsgTrace;
}
public void setEnableMsgTrace(boolean enableMsgTrace) {
this.enableMsgTrace = enableMsgTrace;
}
public String getCustomizedTraceTopic() {
return customizedTraceTopic;
}
public void setCustomizedTraceTopic(String customizedTraceTopic) {
this.customizedTraceTopic = customizedTraceTopic;
}
} }

View File

@ -27,7 +27,12 @@ public class RocketMQProducerProperties {
private Boolean enabled = true; private Boolean enabled = true;
/** /**
* Maximum allowed message size in bytes {@link DefaultMQProducer#maxMessageSize} * Name of producer.
*/
private String group;
/**
* Maximum allowed message size in bytes {@link DefaultMQProducer#maxMessageSize}.
*/ */
private Integer maxMessageSize = 1024 * 1024 * 4; private Integer maxMessageSize = 1024 * 1024 * 4;
@ -70,6 +75,14 @@ public class RocketMQProducerProperties {
*/ */
private boolean retryNextServer = false; private boolean retryNextServer = false;
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Boolean getEnabled() { public Boolean getEnabled() {
return enabled; return enabled;
} }

View File

@ -56,7 +56,7 @@ public class RocketMQAutoConfigurationTests {
public void testProperties() { public void testProperties() {
RocketMQBinderConfigurationProperties binderConfigurationProperties = context RocketMQBinderConfigurationProperties binderConfigurationProperties = context
.getBean(RocketMQBinderConfigurationProperties.class); .getBean(RocketMQBinderConfigurationProperties.class);
assertThat(binderConfigurationProperties.getNamesrvAddr()) assertThat(binderConfigurationProperties.getNameServer())
.isEqualTo("127.0.0.1:9876"); .isEqualTo("127.0.0.1:9876");
RocketMQExtendedBindingProperties bindingProperties = context RocketMQExtendedBindingProperties bindingProperties = context
.getBean(RocketMQExtendedBindingProperties.class); .getBean(RocketMQExtendedBindingProperties.class);