This is an automated email from the ASF dual-hosted git repository.
zhangzicheng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shenyu.git
The following commit(s) were added to refs/heads/master by this push:
new e66f0e31f [ISSUE #3932]refactor shenyu-client-springcloud (#4001)
e66f0e31f is described below
commit e66f0e31f8cf6694d3e24d692b8ba7a5a53e9506
Author: Zihao Huang <[email protected]>
AuthorDate: Tue Sep 27 21:17:08 2022 +0800
[ISSUE #3932]refactor shenyu-client-springcloud (#4001)
* [ISSUE #3932]refactor shenyu-client-springcloud
---
.../springcloud/init/ContextRegisterListener.java | 128 -------------
.../init/SpringCloudClientEventListener.java | 197 ++++++++++-----------
.../init/ContextRegisterListenerTest.java | 95 ----------
.../init/SpringCloudClientEventListenerTest.java | 10 +-
.../ShenyuSpringCloudClientConfiguration.java | 13 --
.../ShenyuSpringCloudClientConfigurationTest.java | 12 --
6 files changed, 101 insertions(+), 354 deletions(-)
diff --git
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListener.java
b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListener.java
deleted file mode 100644
index 150a922c0..000000000
---
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListener.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.apache.shenyu.client.springcloud.init;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.shenyu.client.core.constant.ShenyuClientConstants;
-import
org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher;
-import
org.apache.shenyu.client.core.exception.ShenyuClientIllegalArgumentException;
-import org.apache.shenyu.common.enums.RpcTypeEnum;
-import org.apache.shenyu.common.utils.IpUtils;
-import org.apache.shenyu.common.utils.PathUtils;
-import org.apache.shenyu.common.utils.PortUtils;
-import org.apache.shenyu.common.utils.UriUtils;
-import org.apache.shenyu.register.common.config.PropertiesConfig;
-import org.apache.shenyu.register.common.dto.MetaDataRegisterDTO;
-import org.apache.shenyu.register.common.dto.URIRegisterDTO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.BeanFactory;
-import org.springframework.beans.factory.BeanFactoryAware;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.core.env.Environment;
-import org.springframework.lang.NonNull;
-
-import java.util.Optional;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * The type Context register listener.
- */
-public class ContextRegisterListener implements
ApplicationListener<ContextRefreshedEvent>, BeanFactoryAware {
-
- private static final Logger LOG =
LoggerFactory.getLogger(ContextRegisterListener.class);
-
- private final ShenyuClientRegisterEventPublisher publisher =
ShenyuClientRegisterEventPublisher.getInstance();
-
- private final AtomicBoolean registered = new AtomicBoolean(false);
-
- private final Boolean isFull;
-
- private final String host;
-
- private final String contextPath;
-
- private final String appName;
-
- private final Integer port;
-
- private BeanFactory beanFactory;
-
- /**
- * Instantiates a new Context register listener.
- *
- * @param config the config
- * @param env the env
- */
- public ContextRegisterListener(final PropertiesConfig config, final
Environment env) {
- Properties props = config.getProps();
- this.isFull =
Boolean.parseBoolean(props.getProperty(ShenyuClientConstants.IS_FULL,
Boolean.FALSE.toString()));
- this.contextPath =
Optional.ofNullable(props.getProperty(ShenyuClientConstants.CONTEXT_PATH)).map(UriUtils::repairData).orElse(null);
- if (Boolean.TRUE.equals(isFull)) {
- if (StringUtils.isBlank(contextPath)) {
- String errorMsg = "http register param must config the
contextPath";
- LOG.error(errorMsg);
- throw new ShenyuClientIllegalArgumentException(errorMsg);
- }
- }
- this.port =
Integer.parseInt(Optional.ofNullable(props.getProperty(ShenyuClientConstants.PORT)).orElseGet(()
-> "-1"));
- this.appName = env.getProperty("spring.application.name");
- this.host = props.getProperty(ShenyuClientConstants.HOST);
- }
-
- @Override
- public void setBeanFactory(final BeanFactory beanFactory) throws
BeansException {
- this.beanFactory = beanFactory;
- }
-
- @Override
- public void onApplicationEvent(@NonNull final ContextRefreshedEvent
webServerInitializedEvent) {
- if (!registered.compareAndSet(false, true)) {
- return;
- }
- if (Boolean.TRUE.equals(isFull)) {
- publisher.publishEvent(buildMetaDataDTO());
- }
- final int mergedPort = port <= 0 ? PortUtils.findPort(beanFactory) :
port;
- publisher.publishEvent(buildUriRegisterDTO(mergedPort));
- }
-
- private URIRegisterDTO buildUriRegisterDTO(final int port) {
- return URIRegisterDTO.builder()
- .contextPath(this.contextPath)
- .appName(appName)
- .host(IpUtils.isCompleteHost(this.host) ? this.host :
IpUtils.getHost(this.host))
- .port(port)
- .rpcType(RpcTypeEnum.SPRING_CLOUD.getName())
- .build();
- }
-
- private MetaDataRegisterDTO buildMetaDataDTO() {
- return MetaDataRegisterDTO.builder()
- .contextPath(contextPath)
- .appName(appName)
- .path(PathUtils.decoratorPathWithSlash(contextPath))
- .rpcType(RpcTypeEnum.SPRING_CLOUD.getName())
- .enabled(true)
- .ruleName(contextPath)
- .build();
- }
-}
diff --git
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListener.java
b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListener.java
index 60dd37c77..f29c50359 100644
---
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListener.java
+++
b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/main/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListener.java
@@ -19,27 +19,26 @@ package org.apache.shenyu.client.springcloud.init;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
+import
org.apache.shenyu.client.core.client.AbstractContextRefreshedEventListener;
import org.apache.shenyu.client.core.constant.ShenyuClientConstants;
-import
org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher;
import
org.apache.shenyu.client.core.exception.ShenyuClientIllegalArgumentException;
import org.apache.shenyu.client.springcloud.annotation.ShenyuSpringCloudClient;
import org.apache.shenyu.common.enums.RpcTypeEnum;
-import org.apache.shenyu.common.utils.UriUtils;
+import org.apache.shenyu.common.exception.ShenyuException;
+import org.apache.shenyu.common.utils.IpUtils;
+import org.apache.shenyu.common.utils.PathUtils;
+import org.apache.shenyu.common.utils.PortUtils;
import org.apache.shenyu.register.client.api.ShenyuClientRegisterRepository;
import org.apache.shenyu.register.common.config.PropertiesConfig;
import org.apache.shenyu.register.common.dto.MetaDataRegisterDTO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.aop.support.AopUtils;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextRefreshedEvent;
+import org.apache.shenyu.register.common.dto.URIRegisterDTO;
+import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
-import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.annotation.Annotation;
@@ -56,94 +55,95 @@ import java.util.stream.Collectors;
/**
* The type Spring cloud client event listener.
*/
-public class SpringCloudClientEventListener implements
ApplicationListener<ContextRefreshedEvent> {
-
- /**
- * api path separator.
- */
- private static final String PATH_SEPARATOR = "/";
-
- private static final Logger LOG =
LoggerFactory.getLogger(SpringCloudClientEventListener.class);
-
- private final ShenyuClientRegisterEventPublisher publisher =
ShenyuClientRegisterEventPublisher.getInstance();
-
- private final String contextPath;
-
+public class SpringCloudClientEventListener extends
AbstractContextRefreshedEventListener<Object, ShenyuSpringCloudClient> {
+
private final Boolean isFull;
private final Environment env;
private final String servletContextPath;
- private final List<Class<? extends Annotation>> mappingAnnotation = new
ArrayList<>(7);
-
- private final String[] pathAttributeNames = new String[]{"path", "value"};
-
+ private final List<Class<? extends Annotation>> mappingAnnotation = new
ArrayList<>(3);
+
/**
* Instantiates a new Spring cloud client bean post processor.
*
- * @param clientConfig the client config
- * @param shenyuClientRegisterRepository the shenyu client register
repository
+ * @param clientConfig the shenyu client config
+ * @param shenyuClientRegisterRepository the shenyuClientRegisterRepository
* @param env the env
*/
public SpringCloudClientEventListener(final PropertiesConfig clientConfig,
final ShenyuClientRegisterRepository
shenyuClientRegisterRepository,
final Environment env) {
- String appName = env.getProperty("spring.application.name");
+ super(clientConfig, shenyuClientRegisterRepository);
Properties props = clientConfig.getProps();
- this.contextPath =
Optional.ofNullable(props.getProperty(ShenyuClientConstants.CONTEXT_PATH)).map(UriUtils::repairData).orElse(null);
- if (StringUtils.isBlank(appName)) {
+ this.env = env;
+ if (StringUtils.isBlank(getAppName())) {
String errorMsg = "spring cloud param must config the appName";
LOG.error(errorMsg);
throw new ShenyuClientIllegalArgumentException(errorMsg);
}
- this.env = env;
this.isFull =
Boolean.parseBoolean(props.getProperty(ShenyuClientConstants.IS_FULL,
Boolean.FALSE.toString()));
this.servletContextPath =
env.getProperty("server.servlet.context-path", "");
mappingAnnotation.add(ShenyuSpringCloudClient.class);
mappingAnnotation.add(RequestMapping.class);
- publisher.start(shenyuClientRegisterRepository);
}
@Override
- public void onApplicationEvent(final ContextRefreshedEvent
contextRefreshedEvent) {
+ protected Map<String, Object> getBeans(final ApplicationContext context) {
// Filter out is not controller out
if (Boolean.TRUE.equals(isFull)) {
- return;
- }
- Map<String, Object> beans =
contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(Controller.class);
- for (Map.Entry<String, Object> entry : beans.entrySet()) {
- handler(entry.getValue());
+ getPublisher().publishEvent(MetaDataRegisterDTO.builder()
+ .contextPath(getContextPath())
+ .appName(getAppName())
+ .path(PathUtils.decoratorPathWithSlash(getContextPath()))
+ .rpcType(RpcTypeEnum.SPRING_CLOUD.getName())
+ .enabled(true)
+ .ruleName(getContextPath())
+ .build());
+ return null;
}
+ return context.getBeansWithAnnotation(Controller.class);
}
- private void handler(final Object bean) {
- Class<?> clazz = bean.getClass();
- if (AopUtils.isAopProxy(bean)) {
- clazz = AopUtils.getTargetClass(bean);
- }
- final ShenyuSpringCloudClient beanShenyuClient =
AnnotatedElementUtils.findMergedAnnotation(clazz,
ShenyuSpringCloudClient.class);
- final String superPath = buildApiSuperPath(clazz, beanShenyuClient);
- // Compatible with previous versions
- if (Objects.nonNull(beanShenyuClient) && superPath.contains("*")) {
- publisher.publishEvent(buildMetaDataDTO(beanShenyuClient,
pathJoin(contextPath, superPath), clazz, null));
- return;
+ @Override
+ protected URIRegisterDTO buildURIRegisterDTO(final ApplicationContext
context, final Map<String, Object> beans) {
+ try {
+ final String host = getHost();
+ final int port =
Integer.parseInt(Optional.ofNullable(getPort()).orElseGet(() -> "-1"));
+ final int mergedPort = port <= 0 ?
PortUtils.findPort(context.getAutowireCapableBeanFactory()) : port;
+ return URIRegisterDTO.builder()
+ .contextPath(getContextPath())
+ .appName(getAppName())
+ .host(IpUtils.isCompleteHost(host) ? host :
IpUtils.getHost(host))
+ .port(mergedPort)
+ .rpcType(RpcTypeEnum.SPRING_CLOUD.getName())
+ .build();
+ } catch (ShenyuException e) {
+ throw new ShenyuException(e.getMessage() + "please config
${shenyu.client.http.props.port} in xml/yml !");
}
- final Method[] methods =
ReflectionUtils.getUniqueDeclaredMethods(clazz);
- for (Method method : methods) {
- final RequestMapping requestMapping =
AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
- ShenyuSpringCloudClient methodShenyuClient =
AnnotatedElementUtils.findMergedAnnotation(method,
ShenyuSpringCloudClient.class);
- methodShenyuClient = Objects.isNull(methodShenyuClient) ?
beanShenyuClient : methodShenyuClient;
- // the result of ReflectionUtils#getUniqueDeclaredMethods contains
methods such as hashCode, wait, toSting
- // add Objects.nonNull(requestMapping) to make sure not register
wrong method
- if (Objects.nonNull(methodShenyuClient) &&
Objects.nonNull(requestMapping)) {
- publisher.publishEvent(buildMetaDataDTO(methodShenyuClient,
buildApiPath(method, superPath, methodShenyuClient), clazz, method));
- }
+ }
+
+ @Override
+ protected void handleMethod(final Object bean, final Class<?> clazz,
+ @Nullable final ShenyuSpringCloudClient
beanShenyuClient, final Method method,
+ final String superPath) {
+ final RequestMapping requestMapping =
AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
+ ShenyuSpringCloudClient methodShenyuClient =
AnnotatedElementUtils.findMergedAnnotation(method,
ShenyuSpringCloudClient.class);
+ methodShenyuClient = Objects.isNull(methodShenyuClient) ?
beanShenyuClient : methodShenyuClient;
+ // the result of ReflectionUtils#getUniqueDeclaredMethods contains
methods such as hashCode, wait, toSting
+ // add Objects.nonNull(requestMapping) to make sure not register wrong
method
+ if (Objects.nonNull(methodShenyuClient) &&
Objects.nonNull(requestMapping)) {
+ getPublisher().publishEvent(buildMetaDataDTO(bean,
methodShenyuClient,
+ buildApiPath(method, superPath, methodShenyuClient),
clazz, method));
}
}
-
- private String buildApiPath(@NonNull final Method method, @NonNull final
String superPath, final ShenyuSpringCloudClient methodShenyuClient) {
- if (Objects.nonNull(methodShenyuClient) &&
StringUtils.isNotBlank(methodShenyuClient.path())) {
+
+ @Override
+ protected String buildApiPath(final Method method, final String superPath,
+ @NonNull final ShenyuSpringCloudClient
methodShenyuClient) {
+ final String contextPath = getContextPath();
+ if (StringUtils.isNotBlank(methodShenyuClient.path())) {
return pathJoin(contextPath, superPath, methodShenyuClient.path());
}
final String path = getPathByMethod(method);
@@ -156,7 +156,7 @@ public class SpringCloudClientEventListener implements
ApplicationListener<Conte
private String getPathByMethod(@NonNull final Method method) {
for (Class<? extends Annotation> mapping : mappingAnnotation) {
final Annotation mergedAnnotation =
AnnotatedElementUtils.findMergedAnnotation(method, mapping);
- final String pathByAnnotation =
getPathByAnnotation(mergedAnnotation, pathAttributeNames);
+ final String pathByAnnotation =
getPathByAnnotation(mergedAnnotation);
if (StringUtils.isNotBlank(pathByAnnotation)) {
return pathByAnnotation;
}
@@ -164,69 +164,64 @@ public class SpringCloudClientEventListener implements
ApplicationListener<Conte
return null;
}
- private String getPathByAnnotation(@Nullable final Annotation annotation,
@NonNull final String... pathAttributeName) {
+ private String getPathByAnnotation(@Nullable final Annotation annotation) {
if (Objects.isNull(annotation)) {
return null;
}
- for (String s : pathAttributeName) {
- final Object value = AnnotationUtils.getValue(annotation, s);
- if (value instanceof String && StringUtils.isNotBlank((String)
value)) {
- return (String) value;
- }
- // Only the first path is supported temporarily
- if (value instanceof String[] && ArrayUtils.isNotEmpty((String[])
value) && StringUtils.isNotBlank(((String[]) value)[0])) {
- return ((String[]) value)[0];
- }
+ final Object value = AnnotationUtils.getValue(annotation, "value");
+ if (value instanceof String && StringUtils.isNotBlank((String) value))
{
+ return (String) value;
+ }
+ if (value instanceof String[] && ArrayUtils.isNotEmpty((String[])
value)
+ && StringUtils.isNotBlank(((String[]) value)[0])) {
+ return ((String[]) value)[0];
}
return null;
}
-
- private String buildApiSuperPath(@NonNull final Class<?> clazz, final
ShenyuSpringCloudClient beanShenyuClient) {
+
+ @Override
+ protected String buildApiSuperPath(final Class<?> clazz, @Nullable final
ShenyuSpringCloudClient beanShenyuClient) {
if (Objects.nonNull(beanShenyuClient) &&
StringUtils.isNotBlank(beanShenyuClient.path())) {
return beanShenyuClient.path();
}
RequestMapping requestMapping = AnnotationUtils.findAnnotation(clazz,
RequestMapping.class);
// Only the first path is supported temporarily
- if (Objects.nonNull(requestMapping) &&
ArrayUtils.isNotEmpty(requestMapping.path()) &&
StringUtils.isNotBlank(requestMapping.path()[0])) {
+ if (Objects.nonNull(requestMapping) &&
ArrayUtils.isNotEmpty(requestMapping.path())
+ && StringUtils.isNotBlank(requestMapping.path()[0])) {
return requestMapping.path()[0];
}
return "";
}
-
- private String pathJoin(@NonNull final String... path) {
- StringBuilder result = new StringBuilder(PATH_SEPARATOR);
- for (String p : path) {
- if (!result.toString().endsWith(PATH_SEPARATOR)) {
- result.append(PATH_SEPARATOR);
- }
- result.append(p.startsWith(PATH_SEPARATOR) ?
p.replaceFirst(PATH_SEPARATOR, "") : p);
- }
- return result.toString();
+
+ @Override
+ protected Class<ShenyuSpringCloudClient> getAnnotationType() {
+ return ShenyuSpringCloudClient.class;
}
-
- private MetaDataRegisterDTO buildMetaDataDTO(final ShenyuSpringCloudClient
shenyuSpringCloudClient,
- final String path, final
Class<?> clazz, final Method method) {
- String appName = env.getProperty("spring.application.name");
- String desc = shenyuSpringCloudClient.desc();
- String configRuleName = shenyuSpringCloudClient.ruleName();
- String ruleName = ("".equals(configRuleName)) ? path : configRuleName;
+
+ @Override
+ protected MetaDataRegisterDTO buildMetaDataDTO(final Object bean,
+ final @NonNull
ShenyuSpringCloudClient shenyuClient,
+ final String path, final
Class<?> clazz, final Method method) {
return MetaDataRegisterDTO.builder()
- .contextPath(StringUtils.defaultIfBlank(this.contextPath,
this.servletContextPath))
- .appName(appName)
+ .contextPath(StringUtils.defaultIfBlank(getContextPath(),
this.servletContextPath))
+ .appName(getAppName())
.serviceName(clazz.getName())
.methodName(Optional.ofNullable(method).map(Method::getName).orElse(null))
.path(path)
- .pathDesc(desc)
+ .pathDesc(shenyuClient.desc())
.parameterTypes(Optional.ofNullable(method)
.map(m -> Arrays.stream(m.getParameterTypes())
.map(Class::getName)
.collect(Collectors.joining(","))
- ).orElse(null))
+ ).orElse(null))
.rpcType(RpcTypeEnum.SPRING_CLOUD.getName())
- .enabled(shenyuSpringCloudClient.enabled())
- .ruleName(ruleName)
+ .enabled(shenyuClient.enabled())
+ .ruleName(StringUtils.defaultIfBlank(shenyuClient.ruleName(),
path))
.build();
}
-}
-
+ @Override
+ public String getAppName() {
+ return env.getProperty("spring.application.name");
+ }
+}
diff --git
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java
b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java
deleted file mode 100644
index 761550c53..000000000
---
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.apache.shenyu.client.springcloud.init;
-
-import org.apache.shenyu.client.core.constant.ShenyuClientConstants;
-import
org.apache.shenyu.client.core.disruptor.ShenyuClientRegisterEventPublisher;
-import
org.apache.shenyu.client.core.exception.ShenyuClientIllegalArgumentException;
-import org.apache.shenyu.common.utils.PortUtils;
-import org.apache.shenyu.register.client.api.ShenyuClientRegisterRepository;
-import org.apache.shenyu.register.common.config.PropertiesConfig;
-import org.junit.Assert;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.MethodOrderer;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestMethodOrder;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.MockedStatic;
-import org.mockito.junit.jupiter.MockitoExtension;
-import org.springframework.beans.factory.BeanFactory;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.core.env.Environment;
-
-import java.util.Properties;
-
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.mockStatic;
-import static org.mockito.Mockito.mock;
-
-/**
- * Test for {@link ContextRegisterListener}.
- */
-@ExtendWith(MockitoExtension.class)
-@TestMethodOrder(MethodOrderer.Alphanumeric.class)
-public final class ContextRegisterListenerTest {
-
- private ContextRegisterListener contextRegisterListener;
-
- @Mock
- private Environment env;
-
- @Mock
- private PropertiesConfig config;
-
- @Mock
- private Properties properties;
-
- @Mock
- private BeanFactory beanFactory;
-
- @BeforeEach
- public void beforeEach() {
- when(config.getProps()).thenReturn(properties);
- when(properties.getProperty(ShenyuClientConstants.IS_FULL,
Boolean.FALSE.toString())).thenReturn(Boolean.TRUE.toString());
-
- // hit throws
- Assert.assertThrows(ShenyuClientIllegalArgumentException.class, () ->
new ContextRegisterListener(config, env));
-
- // hit success
-
when(properties.getProperty(ShenyuClientConstants.CONTEXT_PATH)).thenReturn(ShenyuClientConstants.CONTEXT_PATH);
- contextRegisterListener = new ContextRegisterListener(config, env);
-
- ShenyuClientRegisterEventPublisher publisher =
ShenyuClientRegisterEventPublisher.getInstance();
- publisher.start(mock(ShenyuClientRegisterRepository.class));
- }
-
- @Test
- public void testSetBeanFactory() {
- contextRegisterListener.setBeanFactory(beanFactory);
- }
-
- @Test
- public void testOnApplicationEvent() {
- MockedStatic<PortUtils> portUtilsMockedStatic =
mockStatic(PortUtils.class);
- portUtilsMockedStatic.when(() ->
PortUtils.findPort(beanFactory)).thenReturn(8080);
-
contextRegisterListener.onApplicationEvent(mock(ContextRefreshedEvent.class));
-
contextRegisterListener.onApplicationEvent(mock(ContextRefreshedEvent.class));
- }
-}
-
diff --git
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListenerTest.java
b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListenerTest.java
index 90fb703f5..3df376fbf 100644
---
a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListenerTest.java
+++
b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientEventListenerTest.java
@@ -88,8 +88,8 @@ public final class SpringCloudClientEventListenerTest {
public void testShenyuBeanProcess() {
registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(),
any(), any())).thenReturn(Optional.of("token"));
// config with full
- SpringCloudClientEventListener springCloudClientEventListener =
buildSpringCloudClienttEventListener(true);
-
springCloudClientEventListener.onApplicationEvent(contextRefreshedEvent);
+ SpringCloudClientEventListener springCloudClientEventListener =
buildSpringCloudClientEventListener(true);
+ springCloudClientEventListener.onApplicationEvent(new
ContextRefreshedEvent(applicationContext));
verify(applicationContext, never()).getBeansWithAnnotation(any());
registerUtilsMockedStatic.close();
}
@@ -98,7 +98,7 @@ public final class SpringCloudClientEventListenerTest {
public void testNormalBeanProcess() {
init();
registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(),
any(), any())).thenReturn(Optional.of("token"));
- SpringCloudClientEventListener springCloudClientEventListener =
buildSpringCloudClienttEventListener(false);
+ SpringCloudClientEventListener springCloudClientEventListener =
buildSpringCloudClientEventListener(false);
springCloudClientEventListener.onApplicationEvent(contextRefreshedEvent);
verify(applicationContext, times(1)).getBeansWithAnnotation(any());
registerUtilsMockedStatic.close();
@@ -110,13 +110,13 @@ public final class SpringCloudClientEventListenerTest {
registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(),
any(), any())).thenReturn(Optional.of("token"));
registerUtilsMockedStatic.when(() -> RegisterUtils.doRegister(any(),
any(), any()))
.thenAnswer((Answer<Void>) invocation -> null);
- SpringCloudClientEventListener springCloudClientEventListener =
buildSpringCloudClienttEventListener(false);
+ SpringCloudClientEventListener springCloudClientEventListener =
buildSpringCloudClientEventListener(false);
springCloudClientEventListener.onApplicationEvent(contextRefreshedEvent);
verify(applicationContext, times(1)).getBeansWithAnnotation(any());
registerUtilsMockedStatic.close();
}
- private SpringCloudClientEventListener
buildSpringCloudClienttEventListener(final boolean full) {
+ private SpringCloudClientEventListener
buildSpringCloudClientEventListener(final boolean full) {
Properties properties = new Properties();
properties.setProperty("contextPath", "/test");
properties.setProperty("isFull", full + "");
diff --git
a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/main/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfiguration.java
b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/main/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfiguration.java
index 4a4ee809b..d8d57f776 100644
---
a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/main/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfiguration.java
+++
b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/main/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfiguration.java
@@ -17,7 +17,6 @@
package org.apache.shenyu.springboot.starter.client.springcloud;
-import org.apache.shenyu.client.springcloud.init.ContextRegisterListener;
import
org.apache.shenyu.client.springcloud.init.SpringCloudClientEventListener;
import org.apache.shenyu.common.enums.RpcTypeEnum;
import org.apache.shenyu.register.client.api.ShenyuClientRegisterRepository;
@@ -51,16 +50,4 @@ public class ShenyuSpringCloudClientConfiguration {
final
Environment env) {
return new
SpringCloudClientEventListener(clientConfig.getClient().get(RpcTypeEnum.SPRING_CLOUD.getName()),
shenyuClientRegisterRepository, env);
}
-
- /**
- * Context register listener.
- *
- * @param clientConfig the client config
- * @param env the env
- * @return the context register listener
- */
- @Bean
- public ContextRegisterListener contextRegisterListener(final
ShenyuClientConfig clientConfig, final Environment env) {
- return new
ContextRegisterListener(clientConfig.getClient().get(RpcTypeEnum.SPRING_CLOUD.getName()),
env);
- }
}
diff --git
a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/test/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfigurationTest.java
b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/test/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfigurationTest.java
index 4dbe1cdf1..37b45c0ac 100644
---
a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/test/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfigurationTest.java
+++
b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-client/shenyu-spring-boot-starter-client-springcloud/src/test/java/org/apache/shenyu/springboot/starter/client/springcloud/ShenyuSpringCloudClientConfigurationTest.java
@@ -17,7 +17,6 @@
package org.apache.shenyu.springboot.starter.client.springcloud;
-import org.apache.shenyu.client.springcloud.init.ContextRegisterListener;
import
org.apache.shenyu.client.springcloud.init.SpringCloudClientEventListener;
import org.apache.shenyu.register.client.http.utils.RegisterUtils;
import org.junit.jupiter.api.BeforeEach;
@@ -70,15 +69,4 @@ public class ShenyuSpringCloudClientConfigurationTest {
});
registerUtilsMockedStatic.close();
}
-
- @Test
- public void testContextRegisterListener() {
- MockedStatic<RegisterUtils> registerUtilsMockedStatic =
mockStatic(RegisterUtils.class);
- registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(),
any(), any())).thenReturn(Optional.ofNullable("token"));
- applicationContextRunner.run(context -> {
- ContextRegisterListener listener =
context.getBean("contextRegisterListener", ContextRegisterListener.class);
- assertNotNull(listener);
- });
- registerUtilsMockedStatic.close();
- }
}