Commit 2ec72594 by liqiuwei

2.0.1

修改matrix模块调整
parent 108db3f3
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
# 介绍
elasticsearch-starter。
# 特点
-
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>elasticsearch-starter</artifactId>
</dependency>
```
# 示例
<?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>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>elasticsearch-starter</artifactId>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-bigdata</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-bigdata</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-bus</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -13,7 +13,7 @@
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>rocketmq-starter</artifactId>
<artifactId>matrix-mq-rocketmq-starter</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -3,13 +3,13 @@
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>
<artifactId>matrix</artifactId>
<artifactId>matrix-client</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>openfeign-starter</artifactId>
<artifactId>matrix-client-openfeign-starter</artifactId>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
......@@ -33,4 +33,5 @@
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
......@@ -4,7 +4,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableFeignClients("com.secoo.mall")
@EnableFeignClients("com.secoo")
public class MatrixFeignAutoConfiguration {
}
......@@ -5,26 +5,15 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>rocketmq-starter</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
<artifactId>matrix-client</artifactId>
<packaging>pom</packaging>
<modules>
<module>matrix-client-openfeign-starter</module>
</modules>
</project>
\ No newline at end of file
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-datahelper</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -12,15 +12,15 @@ import java.util.concurrent.TimeUnit;
/**
* @author QIANG
* @since 2.0.1 Deprecated。推荐使用RedisHelper
*/
@Deprecated
public class MatrixRedisClusterUtils {
private static MatrixRedisClusterUtils cacheUtils;
@Resource
private RedisTemplate<String, String> redisTemplate;
public static RedisTemplate<String, String> getRedisTemplate() {
return cacheUtils.redisTemplate;
}
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-datahelper</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
package com.secoo.mall.redis.spring.boot.autoconfigure;
import com.secoo.mall.redis.helper.RedisHelper;
import com.secoo.mall.redis.utils.MatrixRedisClusterUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
......@@ -11,6 +12,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
......@@ -27,7 +30,7 @@ public class MatrixeRedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = {"redisTemplate"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
......@@ -38,4 +41,23 @@ public class MatrixeRedisAutoConfiguration {
public RedisHelper redisHelper(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
return new RedisHelper(redisTemplate);
}
/**
* @since 2.0.1 Deprecated,请使用RedisHelper
* @param redisTemplate
* @return
*/
@Bean
@ConditionalOnMissingBean(MatrixRedisClusterUtils.class)
@Deprecated
public MatrixRedisClusterUtils jedisClusterUtils(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
return new MatrixRedisClusterUtils();
}
}
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -21,7 +21,7 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-datahelper-redis-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-datasource</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-datasource</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -21,7 +21,7 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-datasource-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-job</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-job</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-job</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -21,12 +21,12 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-job-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-job-xxl-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo</groupId>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-mq</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-mq</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
package com.secoo.mall.rocketmq.converter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.ContentTypeResolver;
import org.springframework.messaging.converter.DefaultContentTypeResolver;
import org.springframework.messaging.converter.SmartMessageConverter;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
/**
* Abstract base class for {@link SmartMessageConverter} implementations including
* support for common properties and a partial implementation of the conversion methods,
* mainly to check if the converter supports the conversion based on the payload class
* and MIME type.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @author Juergen Hoeller
* @since 4.0
*/
public abstract class AbstractMessageConverter implements SmartMessageConverter {
protected final Log logger = LogFactory.getLog(getClass());
private final List<MimeType> supportedMimeTypes = new ArrayList<>(4);
@Nullable
private ContentTypeResolver contentTypeResolver = new DefaultContentTypeResolver();
private boolean strictContentTypeMatch = false;
private Class<?> serializedPayloadClass = byte[].class;
/**
* Constructor with a single MIME type.
* @param supportedMimeType the supported MIME type
*/
protected AbstractMessageConverter(MimeType supportedMimeType) {
this(Collections.singletonList(supportedMimeType));
}
/**
* Constructor with one or more MIME types via vararg.
* @param supportedMimeTypes the supported MIME types
* @since 5.2.2
*/
protected AbstractMessageConverter(MimeType... supportedMimeTypes) {
this(Arrays.asList(supportedMimeTypes));
}
/**
* Constructor with a Collection of MIME types.
* @param supportedMimeTypes the supported MIME types
*/
protected AbstractMessageConverter(Collection<MimeType> supportedMimeTypes) {
this.supportedMimeTypes.addAll(supportedMimeTypes);
}
/**
* Return the supported MIME types.
*/
public List<MimeType> getSupportedMimeTypes() {
return Collections.unmodifiableList(this.supportedMimeTypes);
}
/**
* Allows sub-classes to add more supported mime types.
* @since 5.2.2
*/
protected void addSupportedMimeTypes(MimeType... supportedMimeTypes) {
this.supportedMimeTypes.addAll(Arrays.asList(supportedMimeTypes));
}
/**
* Configure the {@link ContentTypeResolver} to use to resolve the content
* type of an input message.
* <p>Note that if no resolver is configured, then
* {@link #setStrictContentTypeMatch(boolean) strictContentTypeMatch} should
* be left as {@code false} (the default) or otherwise this converter will
* ignore all messages.
* <p>By default, a {@code DefaultContentTypeResolver} instance is used.
*/
public void setContentTypeResolver(@Nullable ContentTypeResolver resolver) {
this.contentTypeResolver = resolver;
}
/**
* Return the configured {@link ContentTypeResolver}.
*/
@Nullable
public ContentTypeResolver getContentTypeResolver() {
return this.contentTypeResolver;
}
/**
* Whether this converter should convert messages for which no content type
* could be resolved through the configured
* {@link org.springframework.messaging.converter.ContentTypeResolver}.
* <p>A converter can configured to be strict only when a
* {@link #setContentTypeResolver contentTypeResolver} is configured and the
* list of {@link #getSupportedMimeTypes() supportedMimeTypes} is not be empty.
* <p>When this flag is set to {@code true}, {@link #supportsMimeType(MessageHeaders)}
* will return {@code false} if the {@link #setContentTypeResolver contentTypeResolver}
* is not defined or if no content-type header is present.
*/
public void setStrictContentTypeMatch(boolean strictContentTypeMatch) {
if (strictContentTypeMatch) {
Assert.notEmpty(getSupportedMimeTypes(), "Strict match requires non-empty list of supported mime types");
Assert.notNull(getContentTypeResolver(), "Strict match requires ContentTypeResolver");
}
this.strictContentTypeMatch = strictContentTypeMatch;
}
/**
* Whether content type resolution must produce a value that matches one of
* the supported MIME types.
*/
public boolean isStrictContentTypeMatch() {
return this.strictContentTypeMatch;
}
/**
* Configure the preferred serialization class to use (byte[] or String) when
* converting an Object payload to a {@link Message}.
* <p>The default value is byte[].
* @param payloadClass either byte[] or String
*/
public void setSerializedPayloadClass(Class<?> payloadClass) {
Assert.isTrue(byte[].class == payloadClass || String.class == payloadClass,
() -> "Payload class must be byte[] or String: " + payloadClass);
this.serializedPayloadClass = payloadClass;
}
/**
* Return the configured preferred serialization payload class.
*/
public Class<?> getSerializedPayloadClass() {
return this.serializedPayloadClass;
}
/**
* Returns the default content type for the payload. Called when
* {@link #toMessage(Object, MessageHeaders)} is invoked without message headers or
* without a content type header.
* <p>By default, this returns the first element of the {@link #getSupportedMimeTypes()
* supportedMimeTypes}, if any. Can be overridden in sub-classes.
* @param payload the payload being converted to message
* @return the content type, or {@code null} if not known
*/
@Nullable
protected MimeType getDefaultContentType(Object payload) {
List<MimeType> mimeTypes = getSupportedMimeTypes();
return (!mimeTypes.isEmpty() ? mimeTypes.get(0) : null);
}
@Override
@Nullable
public final Object fromMessage(Message<?> message, Class<?> targetClass) {
return fromMessage(message, targetClass, null);
}
@Override
@Nullable
public final Object fromMessage(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
if (!canConvertFrom(message, targetClass)) {
return null;
}
return convertFromInternal(message, targetClass, conversionHint);
}
protected boolean canConvertFrom(Message<?> message, Class<?> targetClass) {
return (supports(targetClass) && supportsMimeType(message.getHeaders()));
}
@Override
@Nullable
public final Message<?> toMessage(Object payload, @Nullable MessageHeaders headers) {
return toMessage(payload, headers, null);
}
@Override
@Nullable
public final Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
if (!canConvertTo(payload, headers)) {
return null;
}
Object payloadToUse = convertToInternal(payload, headers, conversionHint);
if (payloadToUse == null) {
return null;
}
MimeType mimeType = getDefaultContentType(payloadToUse);
if (headers != null) {
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class);
if (accessor != null && accessor.isMutable()) {
if (mimeType != null) {
accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
}
return MessageBuilder.createMessage(payloadToUse, accessor.getMessageHeaders());
}
}
MessageBuilder<?> builder = MessageBuilder.withPayload(payloadToUse);
if (headers != null) {
builder.copyHeaders(headers);
}
if (mimeType != null) {
builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
}
return builder.build();
}
protected boolean canConvertTo(Object payload, @Nullable MessageHeaders headers) {
return (supports(payload.getClass()) && supportsMimeType(headers));
}
protected boolean supportsMimeType(@Nullable MessageHeaders headers) {
if (getSupportedMimeTypes().isEmpty()) {
return true;
}
MimeType mimeType = getMimeType(headers);
if (mimeType == null) {
return !isStrictContentTypeMatch();
}
for (MimeType current : getSupportedMimeTypes()) {
if (current.getType().equals(mimeType.getType()) && current.getSubtype().equals(mimeType.getSubtype())) {
return true;
}
}
return false;
}
@Nullable
protected MimeType getMimeType(@Nullable MessageHeaders headers) {
return (headers != null && this.contentTypeResolver != null ? this.contentTypeResolver.resolve(headers) : null);
}
/**
* Whether the given class is supported by this converter.
* @param clazz the class to test for support
* @return {@code true} if supported; {@code false} otherwise
*/
protected abstract boolean supports(Class<?> clazz);
/**
* Convert the message payload from serialized form to an Object.
* @param message the input message
* @param targetClass the target class for the conversion
* @param conversionHint an extra object passed to the {@link org.springframework.messaging.converter.MessageConverter},
* e.g. the associated {@code MethodParameter} (may be {@code null}}
* @return the result of the conversion, or {@code null} if the converter cannot
* perform the conversion
* @since 4.2
*/
@Nullable
protected Object convertFromInternal(
Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
return null;
}
/**
* cannot perform the conversion
* @since 4.2
*/
@Nullable
protected Object convertToInternal(
Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
return null;
}
\ No newline at end of file
package com.secoo.mall.rocketmq.converter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import org.springframework.lang.Nullable;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.util.ClassUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.MimeType;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON;
import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN;
/**
* An {@code MessageConverter} that reads and writes
* {@link com.google.protobuf.Message com.google.protobuf.Messages} using
* <a href="https://developers.google.com/protocol-buffers/">Google Protocol Buffers</a>.
*
* <p>To generate {@code Message} Java classes, you need to install the {@code protoc} binary.
*
* <p>This converter supports by default {@code "application/x-protobuf"} with the official
* {@code "com.google.protobuf:protobuf-java"} library.
*
* <p>{@code "application/json"} can be supported with the official
* {@code "com.google.protobuf:protobuf-java-util"} 3.x, with 3.3 or higher recommended.
*
* @author Parviz Rozikov
* @author Rossen Stoyanchev
* @since 5.2.2
*/
public class ProtobufMessageConverter extends AbstractMessageConverter {
/**
* The default charset used by the converter.
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* The mime-type for protobuf {@code application/x-protobuf}.
*/
public static final MimeType PROTOBUF = new MimeType("application", "x-protobuf", DEFAULT_CHARSET);
private static final Map<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>();
final ExtensionRegistry extensionRegistry;
@Nullable
private final ProtobufFormatSupport protobufFormatSupport;
/**
* Constructor with a default instance of {@link ExtensionRegistry}.
*/
public ProtobufMessageConverter() {
this(null, null);
}
/**
* Constructor with a given {@code ExtensionRegistry}.
*/
public ProtobufMessageConverter(ExtensionRegistry extensionRegistry) {
this(null, extensionRegistry);
}
ProtobufMessageConverter(@Nullable ProtobufFormatSupport formatSupport,
@Nullable ExtensionRegistry extensionRegistry) {
super(PROTOBUF, TEXT_PLAIN);
if (formatSupport != null) {
this.protobufFormatSupport = formatSupport;
} else if (ClassUtils.isPresent("com.google.protobuf.util.JsonFormat", getClass().getClassLoader())) {
this.protobufFormatSupport = new ProtobufJavaUtilSupport(null, null);
} else {
this.protobufFormatSupport = null;
}
if (this.protobufFormatSupport != null) {
addSupportedMimeTypes(this.protobufFormatSupport.supportedMediaTypes());
}
this.extensionRegistry = (extensionRegistry == null ? ExtensionRegistry.newInstance() : extensionRegistry);
}
@Override
protected boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
@Override
protected boolean canConvertTo(Object payload, @Nullable MessageHeaders headers) {
MimeType mimeType = getMimeType(headers);
return (super.canConvertTo(payload, headers) ||
this.protobufFormatSupport != null && this.protobufFormatSupport.supportsWriteOnly(mimeType));
}
@Override
protected Object convertFromInternal(org.springframework.messaging.Message<?> message,
Class<?> targetClass, @Nullable Object conversionHint) {
MimeType contentType = getMimeType(message.getHeaders());
final Object payload = message.getPayload();
if (contentType == null) {
contentType = PROTOBUF;
}
Charset charset = contentType.getCharset();
if (charset == null) {
charset = DEFAULT_CHARSET;
}
Message.Builder builder = getMessageBuilder(targetClass);
try {
if (PROTOBUF.isCompatibleWith(contentType)) {
builder.mergeFrom((byte[]) payload, this.extensionRegistry);
} else if (this.protobufFormatSupport != null) {
this.protobufFormatSupport.merge(message, charset, contentType, this.extensionRegistry, builder);
}
} catch (IOException ex) {
throw new MessageConversionException(message, "Could not read proto message" + ex.getMessage(), ex);
}
return builder.build();
}
@Override
protected Object convertToInternal(
Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
final Message message = (Message) payload;
MimeType contentType = getMimeType(headers);
if (contentType == null) {
contentType = PROTOBUF;
}
Charset charset = contentType.getCharset();
if (charset == null) {
charset = DEFAULT_CHARSET;
}
try {
if (PROTOBUF.isCompatibleWith(contentType)) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
message.writeTo(byteArrayOutputStream);
payload = byteArrayOutputStream.toByteArray();
} else if (this.protobufFormatSupport != null) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
this.protobufFormatSupport.print(message, outputStream, contentType, charset);
payload = outputStream.toString(charset.name());
}
} catch (IOException ex) {
throw new MessageConversionException("Failed to print Protobuf message: " + ex.getMessage(), ex);
}
return payload;
}
/**
* Create a new {@code Message.Builder} instance for the given class.
* <p>This method uses a ConcurrentReferenceHashMap for caching method lookups.
*/
private Message.Builder getMessageBuilder(Class<?> clazz) {
try {
Method method = methodCache.get(clazz);
if (method == null) {
method = clazz.getMethod("newBuilder");
methodCache.put(clazz, method);
}
return (Message.Builder) method.invoke(clazz);
} catch (Exception ex) {
throw new MessageConversionException(
"Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex);
}
}
/**
* Protobuf format support.
*/
interface ProtobufFormatSupport {
MimeType[] supportedMediaTypes();
boolean supportsWriteOnly(@Nullable MimeType mediaType);
void merge(org.springframework.messaging.Message<?> message,
Charset charset, MimeType contentType, ExtensionRegistry extensionRegistry,
Message.Builder builder) throws IOException, MessageConversionException;
void print(Message message, OutputStream output, MimeType contentType, Charset charset)
throws IOException, MessageConversionException;
}
/**
* {@link ProtobufFormatSupport} implementation used when
* {@code com.google.protobuf.util.JsonFormat} is available.
*/
static class ProtobufJavaUtilSupport implements ProtobufFormatSupport {
private final JsonFormat.Parser parser;
private final JsonFormat.Printer printer;
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this.parser = (parser != null ? parser : JsonFormat.parser());
this.printer = (printer != null ? printer : JsonFormat.printer());
}
@Override
public MimeType[] supportedMediaTypes() {
return new MimeType[]{APPLICATION_JSON};
}
@Override
public boolean supportsWriteOnly(@Nullable MimeType mimeType) {
return false;
}
@Override
public void merge(org.springframework.messaging.Message<?> message, Charset charset,
MimeType contentType, ExtensionRegistry extensionRegistry, Message.Builder builder)
throws IOException, MessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
this.parser.merge(message.getPayload().toString(), builder);
} else {
throw new MessageConversionException(
"protobuf-java-util does not support parsing " + contentType);
}
}
@Override
public void print(Message message, OutputStream output, MimeType contentType, Charset charset)
throws IOException, MessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
OutputStreamWriter writer = new OutputStreamWriter(output, charset);
this.printer.appendTo(message, writer);
writer.flush();
} else {
throw new MessageConversionException(
"protobuf-java-util does not support printing " + contentType);
}
}
}
}
\ No newline at end of file
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-mq</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -27,7 +27,7 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mq-rocketmq-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-mybatis</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-mybatis</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -25,17 +25,17 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mybatis-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-datasource-druid</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mybatis-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-protocol</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-protocol</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-protocol</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-protocol</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix-protocol</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......
......@@ -5,7 +5,7 @@
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -29,27 +29,27 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-web-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-dubbo-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-web-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-dubbo-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<!-- Aapche Dubbo -->
......
# 介绍
mongodb-starter
# 特点
-
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>mongodb-starter</artifactId>
</dependency>
```
# 示例
<?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>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mongodb-starter</artifactId>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
# 介绍
monitor-starter
# 特点
-
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>monitor-starter</artifactId>
</dependency>
```
# 示例
<?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>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>monitor-starter</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.secoo.matrix.monitor.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MonitorAutoConfiguration {
}
package com.secoo.matrix.monitor.constant;
/**
* @author qianglu
*/
public interface MonitorConstant {
String DEFAULT_PORT = "0000";
String DEFAULT_IP = "127.0.0.1";
String TRACE_ID = "traceId";
String RPC_ID = "rpcId";
String APPLICATION = "application";
String INTERFACE = "interface";
String METHOD = "method";
String GROUP = "group";
String VERSION = "version";
String CONSUMER = "consumer";
String PROVIDER = "provider";
String TIMESTAMP = "timestamp";
String SUCCESS = "success";
String FAILURE = "failure";
String ROLE = "Dubbo-RPC";
String ERROR_MSG = "errorMsg";
}
package com.secoo.matrix.monitor.filter;
import com.secoo.matrix.monitor.utils.TraceIDUtils;
import javax.servlet.*;
import java.io.IOException;
/**
* @author qianglu
*/
public class HttpTraceFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
TraceIDUtils.continueTraceID();
filterChain.doFilter(servletRequest, servletResponse);
} catch (Exception e) {
}
}
@Override
public void destroy() {
}
}
package com.secoo.matrix.monitor.filter;
import com.secoo.matrix.monitor.constant.MonitorConstant;
import com.secoo.matrix.monitor.utils.TraceIDUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
/**
* @author QIANGLU
*/
@Activate(group = {MonitorConstant.CONSUMER, MonitorConstant.PROVIDER}, order = -1)
public class LoggerFilter implements Filter {
private Logger LOG = LoggerFactory.getLogger(getClass());
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
RpcContext rpcContext = RpcContext.getContext();
URL url = rpcContext.getUrl();
try {
String who = url.getParameter("side");
//CONSUMER 从MDC中获取RPCID并增加其序列,传递最新序列唯一ID到下一层
if (MonitorConstant.CONSUMER.equals(who)) {
String traceId = TraceIDUtils.continueTraceID();
rpcContext.setAttachment(MonitorConstant.TRACE_ID, traceId);
} else if (MonitorConstant.PROVIDER.equals(who)) {
MDC.remove(MonitorConstant.TRACE_ID);
MDC.remove("rpcId");
String traceId = rpcContext.getAttachment(MonitorConstant.TRACE_ID);
TraceIDUtils.childTraceID(traceId);
}
} catch (Exception e) {
}
return invoker.invoke(invocation);
}
}
package com.secoo.matrix.monitor.http;
import com.secoo.matrix.monitor.utils.TraceIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author qianglu
* <p>
* 为了在Http请求入口生成TRACE_ID,日志ID
* </p>
*/
public class TraceInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(TraceInterceptor.class);
private final ConcurrentMap<String, AtomicInteger> concurrents = new ConcurrentHashMap<>();
private ThreadLocal<Long> stime = new ThreadLocal<>();
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
try {
TraceIDUtils.continueTraceID();
// Long startTime = System.currentTimeMillis();
// stime.set(startTime);
// // 并发计数
// getConcurrent(request).incrementAndGet();
} catch (Exception e) {//容灾
}
return true;
}
/**
* This implementation is empty.
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
/**
* This implementation is empty.
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
try {
MDC.clear();
getConcurrent(request).decrementAndGet();
} catch (Exception e) {
}
}
// 获取并发计数器
private AtomicInteger getConcurrent(HttpServletRequest request) {
String key = request.getRequestURI();
AtomicInteger concurrent = concurrents.get(key);
if (concurrent == null) {
concurrents.putIfAbsent(key, new AtomicInteger());
concurrent = concurrents.get(key);
}
return concurrent;
}
}
package com.secoo.matrix.monitor.utils;
import com.secoo.matrix.monitor.constant.MonitorConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.math.BigDecimal;
/**
* 服务调用追踪号工具类
* 会使用到MDC
* <p>
* 规则:首层调用开始rpcId为"0.0"(TraceID已经生成),
* 如果有跨应用调用
* 1.调用方consumer会将rpcId追加1,例如0.0->0.1,并随RPCContext传递给下一层
* 2.服务方provider收到RPCContext,取出requestId放到本地MDC中并追加本地rpcId层级
* 例如,0.1->0.1.0
* </p>
*
* @author qianglu
*/
public class TraceIDUtils {
private static Logger log = LoggerFactory.getLogger(TraceIDUtils.class);
private final static String ZERO_DOT_ZERO = "0.0";
private final static String ZERO_DOT_ONE = "0.1";
private final static String ZERO_DOT_ONE_ZERO = "0.1.0";
private final static String H_BAR = "-";//横杠
/**
* 首次创建TraceID为UUID+"0.0",RpcID的初始值为"0.0"
*/
public static String createTraceID() {
StringBuilder sb = new StringBuilder();
String requestId = sb.append(UUIDUtils.randomUUID().toString()).append(H_BAR)
.append(ZERO_DOT_ZERO).toString();
MDC.put(MonitorConstant.TRACE_ID, requestId);
MDC.put(MonitorConstant.RPC_ID, ZERO_DOT_ZERO);
log.debug("Create New TraceID is [{}],RPCID is [{}]", requestId, ZERO_DOT_ZERO);
return requestId;
}
/**
* 追踪ID子层级追加,兼顾生成追踪ID
*
* @return
*/
public static String continueTraceID() {
StringBuilder sb = new StringBuilder();
//直接从本地MDC获取requestId
String traceID = MDC.get(MonitorConstant.TRACE_ID);
/*如果为空就生成一个新的.
* 之所以没有,可能服务消费者本身没有requestId初始化入口,所以这里补足
* requestId为UUID+"0.0"从0开始并赋值到本地MDC中,因为此方法为RPC调用下一级生成ID,所以返回的是UUID+"0.1"
* rpcId从"0.1"开始
* */
if (StringUtils.isEmpty(traceID) || "null".equals(traceID)) {
traceID = UUIDUtils.randomUUID().toString();
MDC.put(MonitorConstant.TRACE_ID, traceID + H_BAR + ZERO_DOT_ZERO);
MDC.put(MonitorConstant.RPC_ID, ZERO_DOT_ONE);
log.debug("There is no [traceID], create new noe![{}] and RPCID is [{}]",
traceID + H_BAR + ZERO_DOT_ZERO, ZERO_DOT_ONE);
return traceID + H_BAR + ZERO_DOT_ONE;
}
String rpcId = MDC.get(MonitorConstant.RPC_ID);
try {
/*正常追踪ID格式应该是 " 唯一字符串(UUID)-传递层次" .*/
String[] temp = traceID.split(H_BAR);
if (temp.length > 2) {
/*其它格式*/
} else if (temp.length == 2) {
if (StringUtils.isEmpty(rpcId)) {
/*如果rpcId为空,就是用requestId后缀层级号*/
MDC.put(MonitorConstant.RPC_ID, temp[1]);
rpcId = temp[1];
}
/*将rpcId,分解,最后一位的层级数值+1*/
String[] nums = rpcId.split("\\.");
for (int i = 0; i < nums.length; i++) {
if (i == (nums.length - 1)) {
sb.append(new BigDecimal(nums[i]).add(new BigDecimal("1")));
} else {
sb.append(nums[i]).append(".");
}
}
rpcId = sb.toString();//新的+1后的rpcId
log.debug("TraceID continued ![{}],and RPCID is [{}]",
temp[0] + "-" + sb.toString(), rpcId);
MDC.put(MonitorConstant.RPC_ID, rpcId);//更新本地MDC中的rpcId
return temp[0] + H_BAR + sb.toString();
} else if (temp.length < 2) {
/*可能不包含行号*/
}
} catch (Exception e) {
log.error("ContinueTraceID is failed!!!", e);
}
return traceID;
}
/**
* RPC调用层级追加
* 子层追加使用".1"来表示
* 例如第一层为0.1,调用一次后下一个应用为0.1.1,
*
* @param traceID
* @return
*/
public static void childTraceID(String traceID) {
StringBuilder sb = new StringBuilder();
if (StringUtils.isEmpty(traceID) || "null".equals(traceID)) {
/*如果为空就生成一个新的.
* 之所以没有,是消费者没有使用相同的requestId机制,所以本地重新生成
* requestId为UUID+"0.1"并赋值到本地MDC中,因为此方法为被调用,所以一定是下一级"
* rpcId从"0.1.0"开始
* */
traceID = sb.append(UUIDUtils.randomUUID().toString()).append(H_BAR)
.append(ZERO_DOT_ONE).toString();
MDC.put(MonitorConstant.TRACE_ID, traceID);
MDC.put(MonitorConstant.RPC_ID, ZERO_DOT_ONE_ZERO);
log.debug("There is no [traceID], create new noe![{}] and RPCID is [{}]", traceID,
ZERO_DOT_ONE_ZERO);
return;
}
String rpcId = MDC.get(MonitorConstant.RPC_ID);
try {
String[] temp = traceID.split(H_BAR);
if (temp.length > 2) {
/*其它格式*/
} else if (temp.length == 2) {
if (StringUtils.isEmpty(rpcId)) {
/*如果rpcId为空,就是用requestId后缀层级号*/
MDC.put(MonitorConstant.RPC_ID, temp[1]);
rpcId = temp[1];
}
rpcId = rpcId + ".0";
//更新本地MDC值,新增TraceID
MDC.put(MonitorConstant.RPC_ID, rpcId);
MDC.put(MonitorConstant.TRACE_ID, traceID);
log.debug("RPC_ID_KEY child is ![{}]", rpcId);
} else if (temp.length < 2) {
/*可能不包含行号*/
}
} catch (Exception e) {
log.error("ChildTraceID is failed!!!", e);
}
}
// public static void main(String[] args) {
//
// Logger log = LoggerFactory.getLogger(TraceIDUtils.class);
//
// TraceIDUtils.createTraceID();
// String s = "e591a82137f04423a4933cb0cff59374-0.2";
// MDC.put("requestId", "e591a82137f04423a4933cb0cff59374-0.0");
// MDC.put("rpcId", "0.2");
// System.out.println(TraceIDUtils.continueTraceID());
// MDC.remove(RPC_ID_KEY);
// TraceIDUtils.childTraceID("");
// }
}
package com.secoo.matrix.monitor.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;
public final class UUIDUtils implements java.io.Serializable,
Comparable<UUIDUtils> {
/**
* Explicit serialVersionUID for interoperability.
*/
private static final long serialVersionUID = -4856846361193249489L;
/*
* The most significant 64 bits of this UUID.
*
* @serial
*/
private final long mostSigBits;
/*
* The least significant 64 bits of this UUID.
*
* @serial
*/
private final long leastSigBits;
/*
* The random number generator used by this class to create random based
* UUIDs. In a holder class to defer initialization until needed.
*/
private static class Holder {
static final SecureRandom numberGenerator = new SecureRandom();
}
// Constructors and Factories
/*
* Private constructor which uses a byte array to construct the new UUID.
*/
private UUIDUtils(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++) {
lsb = (lsb << 8) | (data[i] & 0xff);
}
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
/**
* Constructs a new {@code UUID} using the specified data.
* {@code mostSigBits} is used for the most significant 64 bits of the
* {@code UUID} and {@code leastSigBits} becomes the least significant 64
* bits of the {@code UUID}.
*
* @param mostSigBits The most significant bits of the {@code UUID}
* @param leastSigBits The least significant bits of the {@code UUID}
*/
public UUIDUtils(long mostSigBits, long leastSigBits) {
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}
/**
* Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
* <p>
* The {@code UUID} is generated using a cryptographically strong pseudo
* random number generator.
*
* @return A randomly generated {@code UUID}
*/
public static UUIDUtils randomUUID() {
SecureRandom ng = Holder.numberGenerator;
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; /* clear version */
randomBytes[6] |= 0x40; /* set to version 4 */
randomBytes[8] &= 0x3f; /* clear variant */
randomBytes[8] |= 0x80; /* set to IETF variant */
return new UUIDUtils(randomBytes);
}
/**
* Static factory to retrieve a type 3 (name based) {@code UUID} based on
* the specified byte array.
*
* @param name A byte array to be used to construct a {@code UUID}
* @return A {@code UUID} generated from the specified array
*/
public static UUIDUtils nameUUIDFromBytes(byte[] name) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
throw new InternalError("MD5 not supported", nsae);
}
byte[] md5Bytes = md.digest(name);
md5Bytes[6] &= 0x0f; /* clear version */
md5Bytes[6] |= 0x30; /* set to version 3 */
md5Bytes[8] &= 0x3f; /* clear variant */
md5Bytes[8] |= 0x80; /* set to IETF variant */
return new UUIDUtils(md5Bytes);
}
/**
* Creates a {@code UUID} from the string standard representation as
* described in the {@link #toString} method.
*
* @param name A string that specifies a {@code UUID}
* @return A {@code UUID} with the specified value
* @throws IllegalArgumentException If name does not conform to the string representation as
* described in {@link #toString}
*/
public static UUIDUtils fromString(String name) {
String[] components = name.split("-");
if (components.length != 5) {
throw new IllegalArgumentException("Invalid UUID string: " + name);
}
for (int i = 0; i < 5; i++) {
components[i] = "0x" + components[i];
}
long mostSigBits = Long.decode(components[0]).longValue();
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[1]).longValue();
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[2]).longValue();
long leastSigBits = Long.decode(components[3]).longValue();
leastSigBits <<= 48;
leastSigBits |= Long.decode(components[4]).longValue();
return new UUIDUtils(mostSigBits, leastSigBits);
}
// Field Accessor Methods
/**
* Returns the least significant 64 bits of this UUID's 128 bit value.
*
* @return The least significant 64 bits of this UUID's 128 bit value
*/
public long getLeastSignificantBits() {
return leastSigBits;
}
/**
* Returns the most significant 64 bits of this UUID's 128 bit value.
*
* @return The most significant 64 bits of this UUID's 128 bit value
*/
public long getMostSignificantBits() {
return mostSigBits;
}
/**
* The version number associated with this {@code UUID}. The version number
* describes how this {@code UUID} was generated.
* <p>
* The version number has the following meaning:
* <ul>
* <li>1 Time-based UUID
* <li>2 DCE security UUID
* <li>3 Name-based UUID
* <li>4 Randomly generated UUID
* </ul>
*
* @return The version number of this {@code UUID}
*/
public int version() {
// Version is bits masked by 0x000000000000F000 in MS long
return (int) ((mostSigBits >> 12) & 0x0f);
}
/**
* The variant number associated with this {@code UUID}. The variant number
* describes the layout of the {@code UUID}.
* <p>
* The variant number has the following meaning:
* <ul>
* <li>0 Reserved for NCS backward compatibility
* <li>2 <a
* href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>
* (Leach-Salz), used by this class
* <li>6 Reserved, Microsoft Corporation backward compatibility
* <li>7 Reserved for future definition
* </ul>
*
* @return The variant number of this {@code UUID}
*/
public int variant() {
// This field is composed of a varying number of bits.
// 0 - - Reserved for NCS backward compatibility
// 1 0 - The IETF aka Leach-Salz variant (used by this class)
// 1 1 0 Reserved, Microsoft backward compatibility
// 1 1 1 Reserved for future definition.
return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63));
}
/**
* The timestamp value associated with this UUID.
*
* <p>
* The 60 bit timestamp value is constructed from the time_low, time_mid,
* and time_hi fields of this {@code UUID}. The resulting timestamp is
* measured in 100-nanosecond units since midnight, October 15, 1582 UTC.
*
* <p>
* The timestamp value is only meaningful in a time-based UUID, which has
* version type 1. If this {@code UUID} is not a time-based UUID then this
* method throws UnsupportedOperationException.
*
* @return The timestamp of this {@code UUID}.
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
*/
public long timestamp() {
if (version() != 1) {
throw new UnsupportedOperationException("Not a time-based UUID");
}
return (mostSigBits & 0x0FFFL) << 48
| ((mostSigBits >> 16) & 0x0FFFFL) << 32 | mostSigBits >>> 32;
}
/**
* The clock sequence value associated with this UUID.
*
* <p>
* The 14 bit clock sequence value is constructed from the clock sequence
* field of this UUID. The clock sequence field is used to guarantee
* temporal uniqueness in a time-based UUID.
*
* <p>
* The {@code clockSequence} value is only meaningful in a time-based UUID,
* which has version type 1. If this UUID is not a time-based UUID then this
* method throws UnsupportedOperationException.
*
* @return The clock sequence of this {@code UUID}
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
*/
public int clockSequence() {
if (version() != 1) {
throw new UnsupportedOperationException("Not a time-based UUID");
}
return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
}
/**
* The node value associated with this UUID.
*
* <p>
* The 48 bit node value is constructed from the node field of this UUID.
* This field is intended to hold the IEEE 802 address of the machine that
* generated this UUID to guarantee spatial uniqueness.
*
* <p>
* The node value is only meaningful in a time-based UUID, which has version
* type 1. If this UUID is not a time-based UUID then this method throws
* UnsupportedOperationException.
*
* @return The node value of this {@code UUID}
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
*/
public long node() {
if (version() != 1) {
throw new UnsupportedOperationException("Not a time-based UUID");
}
return leastSigBits & 0x0000FFFFFFFFFFFFL;
}
// Object Inherited Methods
/**
* Returns a {@code String} object representing this {@code UUID}.
*
* <p>
* The UUID string representation is as described by this BNF: <blockquote>
*
* <pre>
* {@code
* UUID = <time_low> "-" <time_mid> "-"
* <time_high_and_version> "-"
* <variant_and_sequence> "-"
* <node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit =
* "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
* | "a" | "b" | "c" | "d" | "e" | "f"
* | "A" | "B" | "C" | "D" | "E" | "F"
* }
* </pre>
*
* </blockquote>
*
* @return A string representation of this {@code UUID}
*/
@Override
public String toString() {
return (digits(mostSigBits >> 32, 8) + digits(mostSigBits >> 16, 4)
+ digits(mostSigBits, 4) + digits(leastSigBits >> 48, 4) + digits(
leastSigBits, 12));
}
/**
* Returns val represented by the specified number of hex digits.
*/
private static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}
/**
* Returns a hash code for this {@code UUID}.
*
* @return A hash code value for this {@code UUID}
*/
@Override
public int hashCode() {
long hilo = mostSigBits ^ leastSigBits;
return ((int) (hilo >> 32)) ^ (int) hilo;
}
/**
* Compares this object to the specified object. The result is {@code true}
* if and only if the argument is not {@code null}, is a {@code UUID}
* object, has the same variant, and contains the same value, bit for bit,
* as this {@code UUID}.
*
* @param obj The object to be compared
* @return {@code true} if the objects are the same; {@code false} otherwise
*/
@Override
public boolean equals(Object obj) {
if ((null == obj) || (obj.getClass() != UUID.class)) {
return false;
}
UUIDUtils id = (UUIDUtils) obj;
return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits);
}
// Comparison Operations
/**
* Compares this UUID with the specified UUID.
*
* <p>
* The first of two UUIDs is greater than the second if the most significant
* field in which the UUIDs differ is greater for the first UUID.
*
* @param val {@code UUID} to which this {@code UUID} is to be compared
* @return -1, 0 or 1 as this {@code UUID} is less than, equal to, or
* greater than {@code val}
*/
@Override
public int compareTo(UUIDUtils val) {
// The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers
return (this.mostSigBits < val.mostSigBits ? -1
: (this.mostSigBits > val.mostSigBits ? 1
: (this.leastSigBits < val.leastSigBits ? -1
: (this.leastSigBits > val.leastSigBits ? 1 : 0))));
}
}
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.secoo.matrix.monitor.config.MonitorAutoConfiguration
\ No newline at end of file
# 介绍
openfeign-starter
# 特点
-
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>openfeign-starter</artifactId>
</dependency>
```
# 示例
......@@ -6,7 +6,7 @@
<groupId>com.secoo.mall</groupId>
<artifactId>matrix</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
<packaging>pom</packaging>
......@@ -14,14 +14,8 @@
<module>common-core</module>
<module>common-util</module>
<module>logger-starter</module>
<module>redis-starter</module>
<module>matrix-mybatis</module>
<module>mongodb-starter</module>
<module>elasticsearch-starter</module>
<module>openfeign-starter</module>
<module>matrix-mq</module>
<module>rocketmq-starter</module>
<module>monitor-starter</module>
<module>config-starter</module>
<module>matrix-protocol</module>
<module>matrix-datasource</module>
......@@ -29,6 +23,7 @@
<module>matrix-bigdata</module>
<module>matrix-bus</module>
<module>matrix-datahelper</module>
<module>matrix-client</module>
</modules>
......@@ -57,130 +52,102 @@
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>logger-starter</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>monitor-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>config-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-util</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>redis-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-datasource-druid</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mybatis-starter</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>mongodb-starter</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>elasticsearch-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mq-rocketmq-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mq-rocketmq-client</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<!--rocketmq-starter废弃,启用matrix-mq-rocketmq-starter-->
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>rocketmq-starter</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mq-rocketmq-starter</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>openfeign-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-dubbo-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-dubbo-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-web-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-web-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-job-xxl-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-job-xxl-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-bigdata-hbase-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<!--redis-->
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-datahelper-redis-core</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-datahelper-redis-starter</artifactId>
<version>1.3.2.RELEASE</version>
<version>2.0.1.RELEASE</version>
</dependency>
<!--普通jar-->
......
# 介绍
redis-starter
# 特点
-
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>redis-starter</artifactId>
</dependency>
```
# 示例
<?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>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>redis-starter</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.secoo.mall.redis.config;
import com.secoo.mall.redis.utils.MatrixRedisClusterUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Created by QIANG
*
* @author QIANG
*/
@Configuration
public class MatrixeRedisAutoConfiguration {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisSerializer stringSerializer = new StringRedisSerializer();
RedisTemplate<String, String> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
return redisTemplate;
}
@Bean
@ConditionalOnMissingBean(MatrixRedisClusterUtils.class)
public MatrixRedisClusterUtils jedisClusterUtils() {
return new MatrixRedisClusterUtils();
}
}
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.secoo.mall.redis.config.MatrixeRedisAutoConfiguration
\ No newline at end of file
package com.secoo.mall.rocketmq.config;
import com.secoo.mall.rocketmq.hook.MatrixConsumeHook;
import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author qianglu
*/
@Configuration
public class MatrixListenerContainerConfiguration implements BeanPostProcessor {
private final static Logger log = LoggerFactory.getLogger(MatrixListenerContainerConfiguration.class);
@Value("${matrix.rocketmq.consumer.delayLevel:0}")
private int delayLevel;
@Bean
MatrixConsumeHook matrixConsumeHook() {
return new MatrixConsumeHook();
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DefaultRocketMQListenerContainer) {
DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;
if (log.isDebugEnabled()) {
log.debug("MatrixListenerContainerConfiguration config setDelayLevelWhenNextConsume value:{}", delayLevel);
}
container.setDelayLevelWhenNextConsume(delayLevel);
container.getConsumer().getDefaultMQPushConsumerImpl().registerConsumeMessageHook(matrixConsumeHook());
}
return bean;
}
}
package com.secoo.mall.rocketmq.config;
import com.secoo.mall.rocketmq.hook.MatrixProducerHook;
import com.secoo.mall.rocketmq.producer.MartixProducer;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.AccessChannel;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* @author qianglu
*/
@Configuration
@Import(MatrixListenerContainerConfiguration.class)
public class MatrixRocketMQAutoConfiguration {
@Bean
public DefaultMQProducer defaultMQProducer(RocketMQProperties rocketMQProperties) {
RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
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");
String accessChannel = rocketMQProperties.getAccessChannel();
MartixProducer producer;
String ak = rocketMQProperties.getProducer().getAccessKey();
String sk = rocketMQProperties.getProducer().getSecretKey();
MatrixProducerHook matrixProducerHook = new MatrixProducerHook();
if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) {
producer = new MartixProducer(groupName, new AclClientRPCHook(new SessionCredentials(ak, sk)),
rocketMQProperties.getProducer().isEnableMsgTrace(),
rocketMQProperties.getProducer().getCustomizedTraceTopic(),matrixProducerHook);
producer.setVipChannelEnabled(false);
} else {
producer = new MartixProducer(groupName, rocketMQProperties.getProducer().isEnableMsgTrace(),
rocketMQProperties.getProducer().getCustomizedTraceTopic(),matrixProducerHook);
}
producer.setNamesrvAddr(nameServer);
if (!StringUtils.isEmpty(accessChannel)) {
producer.setAccessChannel(AccessChannel.valueOf(accessChannel));
}
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;
}
}
package com.secoo.mall.rocketmq.hook;
import org.apache.rocketmq.client.hook.ConsumeMessageContext;
import org.apache.rocketmq.client.hook.ConsumeMessageHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author qianglu
*/
public class MatrixConsumeHook implements ConsumeMessageHook {
private final static Logger log = LoggerFactory.getLogger(MatrixConsumeHook.class);
@Override
public String hookName() {
return "MatrixConsumeHook";
}
@Override
public void consumeMessageBefore(ConsumeMessageContext context) {
}
@Override
public void consumeMessageAfter(ConsumeMessageContext context) {
try {
log.info("consumeMessageAfter,Succ:{} Topic:{},TraceContext:{},ConsumerGroup:{}", context.isSuccess(), context.getMq().getTopic(), context.getMqTraceContext(), context.getConsumerGroup());
} catch (Exception e) {//防灾冗余
}
}
}
package com.secoo.mall.rocketmq.hook;
import org.apache.rocketmq.client.hook.SendMessageContext;
import org.apache.rocketmq.client.hook.SendMessageHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author qianglu
*/
public class MatrixProducerHook implements SendMessageHook {
private final static Logger log = LoggerFactory.getLogger(MatrixProducerHook.class);
@Override
public String hookName() {
return "MatrixProducerHook";
}
@Override
public void sendMessageBefore(SendMessageContext context) {
}
@Override
public void sendMessageAfter(SendMessageContext context) {
try {
log.info("sendMessageAfter,TraceContext:{},Mode:{},Topic:{},Targs:{},ProducerGroup:{},BrokerAddr:{},Namespace:{},Exception:{}", context.getMqTraceContext(), context.getCommunicationMode().name(), context.getMessage().getTopic(), context.getMessage().getTags(), context.getProducerGroup(), context.getBrokerAddr(), context.getNamespace(), context.getException() == null ? null : context.getException().getMessage());
} catch (Exception e) {//防灾冗余}
}
}
}
\ No newline at end of file
package com.secoo.mall.rocketmq.producer;
import org.apache.rocketmq.client.hook.SendMessageHook;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.remoting.RPCHook;
/**
* @author qianglu
*/
public class MartixProducer extends DefaultMQProducer {
public MartixProducer(final String producerGroup, RPCHook rpcHook, boolean enableMsgTrace,
final String customizedTraceTopic, SendMessageHook messageHook) {
super(producerGroup, rpcHook, enableMsgTrace, customizedTraceTopic);
this.defaultMQProducerImpl.registerSendMessageHook(messageHook);
}
public MartixProducer(final String producerGroup, boolean enableMsgTrace, final String customizedTraceTopic, SendMessageHook messageHook) {
super(producerGroup, enableMsgTrace, customizedTraceTopic);
this.defaultMQProducerImpl.registerSendMessageHook(messageHook);
}
}
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.secoo.mall.rocketmq.config.MatrixRocketMQAutoConfiguration
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment