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

Merge pull request #431 from fangjian0423/master

Fix bug 4 spring-cloud-starter-bus-rocketmq
This commit is contained in:
Xiaolong Zuo 2019-03-15 17:26:46 +08:00 committed by GitHub
commit 09e90a1e67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 147 additions and 115 deletions

View File

@ -16,8 +16,6 @@
*/ */
package org.springframework.cloud.alibaba.cloud.examples.rocketmq; package org.springframework.cloud.alibaba.cloud.examples.rocketmq;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -30,6 +28,9 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/** /**
* RocketMQ Bus Spring Application * RocketMQ Bus Spring Application
* *
@ -41,54 +42,61 @@ import org.springframework.web.bind.annotation.RestController;
@RemoteApplicationEventScan(basePackages = "org.springframework.cloud.alibaba.cloud.examples.rocketmq") @RemoteApplicationEventScan(basePackages = "org.springframework.cloud.alibaba.cloud.examples.rocketmq")
public class RocketMQBusApplication { public class RocketMQBusApplication {
public static void main(String[] args) { public static void main(String[] args) {
new SpringApplicationBuilder(RocketMQBusApplication.class) new SpringApplicationBuilder(RocketMQBusApplication.class)
.properties("server.port=0") // Random server port .properties("server.port=0") // Random server port
.properties("management.endpoints.web.exposure.include=*") // exposure includes all .properties("management.endpoints.web.exposure.include=*") // exposure
.properties("spring.cloud.bus.trace.enabled=true") // Enable trace // includes
.run(args); // all
} .properties("spring.cloud.bus.trace.enabled=true") // Enable trace
.run(args);
}
@Autowired @Autowired
private ApplicationEventPublisher publisher; private ApplicationEventPublisher publisher;
@Value("${spring.cloud.bus.id}") @Value("${spring.cloud.bus.id}")
private String originService; private String originService;
@Value("${server.port}") @Value("${server.port}")
private int localServerPort; private int localServerPort;
@Autowired @Autowired
private ObjectMapper objectMapper; private ObjectMapper objectMapper;
/** /**
* Publish the {@link UserRemoteApplicationEvent} * Publish the {@link UserRemoteApplicationEvent}
* *
* @param name the user name * @param name the user name
* @param destination the destination * @param destination the destination
* @return If published * @return If published
*/ */
@GetMapping("/bus/event/publish/user") @GetMapping("/bus/event/publish/user")
public boolean publish(@RequestParam String name, @RequestParam(required = false) String destination) { public boolean publish(@RequestParam String name,
User user = new User(); @RequestParam(required = false) String destination) {
user.setId(System.currentTimeMillis()); User user = new User();
user.setName(name); user.setId(System.currentTimeMillis());
publisher.publishEvent(new UserRemoteApplicationEvent(user, originService, destination)); user.setName(name);
return true; publisher.publishEvent(
} new UserRemoteApplicationEvent(this, user, originService, destination));
return true;
}
/** /**
* Listener on the {@link UserRemoteApplicationEvent} * Listener on the {@link UserRemoteApplicationEvent}
* *
* @param event {@link UserRemoteApplicationEvent} * @param event {@link UserRemoteApplicationEvent}
*/ */
@EventListener @EventListener
public void onEvent(UserRemoteApplicationEvent event) { public void onEvent(UserRemoteApplicationEvent event) {
System.out.printf("Server [port : %d] listeners on %s\n", localServerPort, event.getUser()); System.out.printf("Server [port : %d] listeners on %s\n", localServerPort,
} event.getUser());
}
@EventListener @EventListener
public void onAckEvent(AckRemoteApplicationEvent event) throws JsonProcessingException { public void onAckEvent(AckRemoteApplicationEvent event)
System.out.printf("Server [port : %d] listeners on %s\n", localServerPort, objectMapper.writeValueAsString(event)); throws JsonProcessingException {
} System.out.printf("Server [port : %d] listeners on %s\n", localServerPort,
objectMapper.writeValueAsString(event));
}
} }

View File

@ -26,12 +26,22 @@ import org.springframework.cloud.bus.event.RemoteApplicationEvent;
*/ */
public class UserRemoteApplicationEvent extends RemoteApplicationEvent { public class UserRemoteApplicationEvent extends RemoteApplicationEvent {
public UserRemoteApplicationEvent(User user, String originService, private User user;
public UserRemoteApplicationEvent() {
}
public UserRemoteApplicationEvent(Object source, User user, String originService,
String destinationService) { String destinationService) {
super(user, originService, destinationService); super(source, originService, destinationService);
this.user = user;
}
public void setUser(User user) {
this.user = user;
} }
public User getUser() { public User getUser() {
return (User) getSource(); return user;
} }
} }

View File

@ -1,4 +1,4 @@
spring.application.name=spring-cloud-bus-rocketmq-example spring.application.name=spring-cloud-bus-rocketmq-example
spring.cloud.stream.rocketmq.binder.namesrv-addr=127.0.0.1:9876 spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
server.port=8080 server.port=8080
spring.cloud.bus.id=${spring.application.name}:${server.port} spring.cloud.bus.id=${spring.application.name}:${server.port}

View File

@ -16,6 +16,11 @@
*/ */
package org.springframework.cloud.bus.rocketmq.env; package org.springframework.cloud.bus.rocketmq.env;
import static org.springframework.cloud.bus.SpringCloudBusClient.INPUT;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.cloud.bus.BusEnvironmentPostProcessor; import org.springframework.cloud.bus.BusEnvironmentPostProcessor;
@ -25,82 +30,88 @@ import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.cloud.bus.SpringCloudBusClient.INPUT;
/** /**
* The lowest precedence {@link EnvironmentPostProcessor} configures default RocketMQ Bus Properties that will be * The lowest precedence {@link EnvironmentPostProcessor} configures default RocketMQ Bus
* appended into {@link SpringApplication#defaultProperties} * Properties that will be appended into {@link SpringApplication#defaultProperties}
* *
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a> * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @see BusEnvironmentPostProcessor * @see BusEnvironmentPostProcessor
* @since 0.2.1 * @since 0.2.1
*/ */
public class RocketMQBusEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public class RocketMQBusEnvironmentPostProcessor
implements EnvironmentPostProcessor, Ordered {
/** /**
* The name of {@link PropertySource} of {@link SpringApplication#defaultProperties} * The name of {@link PropertySource} of {@link SpringApplication#defaultProperties}
*/ */
private static final String PROPERTY_SOURCE_NAME = "defaultProperties"; private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
@Override @Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
addDefaultPropertySource(environment); addDefaultPropertySource(environment);
} }
private void addDefaultPropertySource(ConfigurableEnvironment environment) { private void addDefaultPropertySource(ConfigurableEnvironment environment) {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
configureDefaultProperties(map); configureDefaultProperties(map);
addOrReplace(environment.getPropertySources(), map); addOrReplace(environment.getPropertySources(), map);
} }
private void configureDefaultProperties(Map<String, Object> source) { private void configureDefaultProperties(Map<String, Object> source) {
// Required Properties // Required Properties
String groupBindingPropertyName = createBindingPropertyName(INPUT, "group"); String groupBindingPropertyName = createBindingPropertyName(INPUT, "group");
source.put(groupBindingPropertyName, "rocketmq-bus-group"); String broadcastingPropertyName = createRocketMQPropertyName(INPUT,
} "broadcasting");
source.put(groupBindingPropertyName, "rocketmq-bus-group");
source.put(broadcastingPropertyName, "true");
}
private String createBindingPropertyName(String channel, String propertyName) { private String createRocketMQPropertyName(String channel, String propertyName) {
return "spring.cloud.stream.bindings." + channel + "." + propertyName; return "spring.cloud.stream.rocketmq.bindings." + INPUT + ".consumer."
} + propertyName;
}
/** private String createBindingPropertyName(String channel, String propertyName) {
* Copy from {@link BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)} return "spring.cloud.stream.bindings." + channel + "." + propertyName;
* }
* @param propertySources {@link MutablePropertySources}
* @param map Default RocketMQ Bus Properties
*/
private void addOrReplace(MutablePropertySources propertySources,
Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
@Override /**
public int getOrder() { * Copy from
return LOWEST_PRECEDENCE; * {@link BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)}
} *
* @param propertySources {@link MutablePropertySources}
* @param map Default RocketMQ Bus Properties
*/
private void addOrReplace(MutablePropertySources propertySources,
Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
} }

View File

@ -83,6 +83,12 @@ public class RocketMQMessageChannelBinder extends
MessageChannel errorChannel) throws Exception { MessageChannel errorChannel) throws Exception {
if (producerProperties.getExtension().getEnabled()) { if (producerProperties.getExtension().getEnabled()) {
// if producerGroup is empty, using destination
String extendedProducerGroup = producerProperties.getExtension().getGroup();
String producerGroup = StringUtils.isEmpty(extendedProducerGroup)
? destination.getName()
: extendedProducerGroup;
RocketMQBinderConfigurationProperties mergedProperties = RocketMQBinderUtils RocketMQBinderConfigurationProperties mergedProperties = RocketMQBinderUtils
.mergeProperties(rocketBinderConfigurationProperties, .mergeProperties(rocketBinderConfigurationProperties,
rocketMQProperties); rocketMQProperties);
@ -111,8 +117,7 @@ public class RocketMQMessageChannelBinder extends
if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) { if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) {
RPCHook rpcHook = new AclClientRPCHook( RPCHook rpcHook = new AclClientRPCHook(
new SessionCredentials(ak, sk)); new SessionCredentials(ak, sk));
producer = new DefaultMQProducer( producer = new DefaultMQProducer(producerGroup, rpcHook,
producerProperties.getExtension().getGroup(), rpcHook,
mergedProperties.isEnableMsgTrace(), mergedProperties.isEnableMsgTrace(),
mergedProperties.getCustomizedTraceTopic()); mergedProperties.getCustomizedTraceTopic());
producer.setVipChannelEnabled(false); producer.setVipChannelEnabled(false);
@ -120,8 +125,7 @@ public class RocketMQMessageChannelBinder extends
RocketMQUtil.getInstanceName(rpcHook, destination.getName())); RocketMQUtil.getInstanceName(rpcHook, destination.getName()));
} }
else { else {
producer = new DefaultMQProducer( producer = new DefaultMQProducer(producerGroup);
producerProperties.getExtension().getGroup());
producer.setVipChannelEnabled( producer.setVipChannelEnabled(
producerProperties.getExtension().getVipChannelEnabled()); producerProperties.getExtension().getVipChannelEnabled());
} }
@ -142,8 +146,7 @@ public class RocketMQMessageChannelBinder extends
} }
RocketMQMessageHandler messageHandler = new RocketMQMessageHandler( RocketMQMessageHandler messageHandler = new RocketMQMessageHandler(
rocketMQTemplate, destination.getName(), rocketMQTemplate, destination.getName(), producerGroup,
producerProperties.getExtension().getGroup(),
producerProperties.getExtension().getTransactional(), producerProperties.getExtension().getTransactional(),
instrumentationManager); instrumentationManager);
messageHandler.setBeanFactory(this.getApplicationContext().getBeanFactory()); messageHandler.setBeanFactory(this.getApplicationContext().getBeanFactory());