Optimize the Appactive module (#3107)

pull/3156/head
YuLuo 2 years ago committed by GitHub
parent 5593d67039
commit a2d91e56c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -90,8 +90,10 @@
<artifactId>fastjson</artifactId>
<version>2.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>

@ -20,16 +20,16 @@ package com.alibaba.cloud.appactive.common;
* @author raozihao, mageekchiu
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
public class ServiceMeta implements Comparable<ServiceMeta> {
public class ServiceMetaEntity implements Comparable<ServiceMetaEntity> {
private String uriPrefix;
private String ra;
public ServiceMeta() {
public ServiceMetaEntity() {
}
public ServiceMeta(String uriPrefix, String ra) {
public ServiceMetaEntity(String uriPrefix, String ra) {
this.uriPrefix = uriPrefix;
this.ra = ra;
}
@ -56,7 +56,7 @@ public class ServiceMeta implements Comparable<ServiceMeta> {
}
@Override
public int compareTo(ServiceMeta o) {
public int compareTo(ServiceMetaEntity o) {
int pre = this.uriPrefix.compareTo(o.getUriPrefix());
return pre == 0 ? this.ra.compareTo(o.getRa()) : pre;
}

@ -24,7 +24,7 @@ import java.util.List;
*/
public class ServiceMetaObject {
private List<ServiceMeta> serviceMetaList;
private List<ServiceMetaEntity> serviceMetaList;
/**
* string of serviceMetaList.
@ -33,7 +33,7 @@ public class ServiceMetaObject {
private String md5OfList;
public ServiceMetaObject(List<ServiceMeta> serviceMetaList, String md5OfList) {
public ServiceMetaObject(List<ServiceMetaEntity> serviceMetaList, String md5OfList) {
this.serviceMetaList = serviceMetaList;
this.md5OfList = md5OfList;
}
@ -41,11 +41,11 @@ public class ServiceMetaObject {
public ServiceMetaObject() {
}
public List<ServiceMeta> getServiceMetaList() {
public List<ServiceMetaEntity> getServiceMetaList() {
return serviceMetaList;
}
public void setServiceMetaList(List<ServiceMeta> serviceMetaList) {
public void setServiceMetaList(List<ServiceMetaEntity> serviceMetaList) {
this.serviceMetaList = serviceMetaList;
}
@ -67,7 +67,7 @@ public class ServiceMetaObject {
@Override
public String toString() {
return "ServiceMetaObject{" + "serviceMetaList=" + serviceMetaList
return "ServiceMetaObject{" + "ServiceMetaEntityList=" + serviceMetaList
+ ", md5OfList='" + md5OfList + '\'' + '}';
}

@ -20,14 +20,29 @@ package com.alibaba.cloud.appactive.constant;
* @author raozihao, mageekchiu
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
public final class Constants {
public final class AppactiveConstants {
/**
* Router Id header key.
*/
public static final String ROUTER_ID_HEADER_KEY = "appactive-router-id";
private Constants() {
/**
* Unit type.
*/
public static final String UT = "ut";
/**
* Meta.
*/
public static final String SVC_META = "svc_meta";
/**
* Version.
*/
public static final String SVC_META_V = "svc_meta_v";
private AppactiveConstants() {
}
}

@ -22,7 +22,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.cloud.appactive.common.ServiceMeta;
import com.alibaba.cloud.appactive.common.ServiceMetaEntity;
import com.alibaba.cloud.appactive.common.UriContext;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.fastjson.JSONObject;
@ -81,10 +81,10 @@ public class AppactivePredicate extends AbstractServerPredicate {
return true;
}
String serviceType = null;
List<ServiceMeta> serviceMetas = JSONObject.parseArray(svcMeta,
ServiceMeta.class);
List<ServiceMetaEntity> serviceMetas = JSONObject.parseArray(svcMeta,
ServiceMetaEntity.class);
Map<String, String> matchingPatterns = new HashMap<>();
for (ServiceMeta sm : serviceMetas) {
for (ServiceMetaEntity sm : serviceMetas) {
if (antPathMatcher.match(sm.getUriPrefix(), uriPath)) {
matchingPatterns.put(sm.getUriPrefix(), sm.getRa());
}

@ -16,15 +16,9 @@
package com.alibaba.cloud.appactive.consumer;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.optionals.OptionalDecoder;
import io.appactive.support.lang.CollectionUtils;
import io.appactive.support.log.LogUtil;
import org.slf4j.Logger;
@ -38,8 +32,6 @@ import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
/**
* @author raozihao, mageekchiu
@ -51,10 +43,7 @@ public class ConsumerAutoConfig {
private static final Logger logger = LogUtil.getLogger();
@Autowired
ApplicationContext context;
@Autowired(required = false)
RestTemplate restTemplate;
private ApplicationContext context;
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@ -67,29 +56,27 @@ public class ConsumerAutoConfig {
}
@Bean
@ConditionalOnMissingBean(name = "feignDecoderPostProcessor")
public BeanPostProcessor feignDecoderPostProcessor() {
return new FeignDecoderPostProcessor(context);
}
@Bean
public RequestInterceptor routerIdTransmissionRequestInterceptor() {
return new RouterIdTransmissionRequestInterceptor();
@ConditionalOnMissingBean(name = "feignRouterIdTransmissionRequestInterceptor")
public RequestInterceptor feignRouterIdTransmissionRequestInterceptor() {
return new FeignRouterIdTransmissionRequestInterceptor();
}
@PostConstruct
public void init() {
if (restTemplate != null) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new ReqResInterceptor());
logger.info(
"ConsumerAutoConfig adding interceptor for restTemplate[{}]......",
restTemplate.getClass());
restTemplate.setInterceptors(interceptors);
@Bean
@ConditionalOnMissingBean(name = "restTemplateStrategyBeanPostProcessor")
public BeanPostProcessor restTemplateStrategyBeanPostProcessor() {
return new RestTemplateStrategyBeanPostProcessor(context);
}
@Bean
@ConditionalOnMissingBean(name = "reactiveRequestStrategyBeanPostProcessor")
public BeanPostProcessor reactiveRequestStrategyBeanPostProcessor() {
return new ReactiveRequestStrategyBeanPostProcessor(context);
}
}

@ -61,7 +61,7 @@ public class FeignDecoderPostProcessor implements BeanPostProcessor {
}
Decoder decoder = (Decoder) bean;
// wrap original decoder
return new ResponseInterceptor(decoder);
return new FeignResponseDecoderInterceptor(decoder);
/// another way
// Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(),

@ -31,13 +31,13 @@ import org.slf4j.Logger;
* @author raozihao, mageekchiu
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
public class ResponseInterceptor implements Decoder {
public class FeignResponseDecoderInterceptor implements Decoder {
private static final Logger logger = LogUtil.getLogger();
final Decoder delegate;
public ResponseInterceptor(Decoder delegate) {
public FeignResponseDecoderInterceptor(Decoder delegate) {
Objects.requireNonNull(delegate, "Decoder must not be null. ");
this.delegate = delegate;
}
@ -46,7 +46,7 @@ public class ResponseInterceptor implements Decoder {
public Object decode(Response response, Type type)
throws IOException, FeignException {
Object object = delegate.decode(response, type);
logger.info("ResponseInterceptor uri {} for request {} got cleared by {}",
logger.info("FeignResponseDecoderInterceptor uri {} for request {} got cleared by {}",
UriContext.getUriPath(), response.request().url(), delegate.getClass());
UriContext.clearContext();
return object;

@ -19,7 +19,7 @@ package com.alibaba.cloud.appactive.consumer;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.cloud.appactive.common.UriContext;
import com.alibaba.cloud.appactive.constant.Constants;
import com.alibaba.cloud.appactive.constant.AppactiveConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.appactive.java.api.base.AppContextClient;
@ -31,7 +31,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
* @author raozihao, mageekchiu
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
public class RouterIdTransmissionRequestInterceptor implements RequestInterceptor {
public class FeignRouterIdTransmissionRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
@ -44,7 +44,7 @@ public class RouterIdTransmissionRequestInterceptor implements RequestIntercepto
if (request == null) {
return;
}
requestTemplate.header(Constants.ROUTER_ID_HEADER_KEY,
requestTemplate.header(AppactiveConstants.ROUTER_ID_HEADER_KEY,
AppContextClient.getRouteId());
// store uri for routing filter
UriContext.setUriPath(requestTemplate.url());

@ -0,0 +1,70 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 com.alibaba.cloud.appactive.consumer;
import javax.validation.constraints.NotNull;
import com.alibaba.cloud.appactive.constant.AppactiveConstants;
import io.appactive.java.api.base.AppContextClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author yuluo
*/
public class ReactiveRequestStrategyBeanPostProcessor implements BeanPostProcessor {
final ApplicationContext applicationContext;
public ReactiveRequestStrategyBeanPostProcessor(
ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(@NotNull Object bean,
@NotNull String beanName) {
if (bean instanceof WebClient || bean instanceof WebClient.Builder) {
assert bean instanceof WebClient;
WebClient webClient = (WebClient) bean;
// add filter
webClient.mutate().filter((request, next) -> {
ClientRequest clientRequest = ClientRequest.from(request)
.headers(headers -> headers.set(
AppactiveConstants.ROUTER_ID_HEADER_KEY,
AppContextClient.getRouteId()))
.build();
return next.exchange(clientRequest);
}).build();
}
return bean;
}
}

@ -19,7 +19,7 @@ package com.alibaba.cloud.appactive.consumer;
import java.io.IOException;
import com.alibaba.cloud.appactive.common.UriContext;
import com.alibaba.cloud.appactive.constant.Constants;
import com.alibaba.cloud.appactive.constant.AppactiveConstants;
import io.appactive.java.api.base.AppContextClient;
import io.appactive.support.log.LogUtil;
import org.slf4j.Logger;
@ -33,7 +33,7 @@ import org.springframework.http.client.ClientHttpResponse;
* @author raozihao, mageekchiu
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
public class ReqResInterceptor implements ClientHttpRequestInterceptor {
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
private static final Logger logger = LogUtil.getLogger();
@ -41,13 +41,13 @@ public class ReqResInterceptor implements ClientHttpRequestInterceptor {
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add(Constants.ROUTER_ID_HEADER_KEY,
request.getHeaders().add(AppactiveConstants.ROUTER_ID_HEADER_KEY,
AppContextClient.getRouteId());
UriContext.setUriPath(request.getURI().getPath());
ClientHttpResponse response = execution.execute(request, body);
logger.info("ReqResInterceptor uri {} for request {} got cleared",
logger.info("RestTemplateInterceptor uri {} for request {} got cleared",
UriContext.getUriPath(), request.getURI());
UriContext.clearContext();
return response;

@ -0,0 +1,55 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 com.alibaba.cloud.appactive.consumer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.client.RestTemplate;
/**
* @author: yuluo
*/
public class RestTemplateStrategyBeanPostProcessor implements BeanPostProcessor {
final ApplicationContext applicationContext;
public RestTemplateStrategyBeanPostProcessor(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean;
// add interceptor
restTemplate.getInterceptors().add(new RestTemplateInterceptor());
}
return bean;
}
}

@ -27,7 +27,7 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.cloud.appactive.constant.Constants;
import com.alibaba.cloud.appactive.constant.AppactiveConstants;
import io.appactive.java.api.base.AppContextClient;
import io.appactive.java.api.base.constants.AppactiveConstant;
import io.appactive.java.api.bridge.servlet.ServletService;
@ -71,7 +71,7 @@ public class CoreServiceFilter implements Filter {
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String routerId = ServletService.getRouteIdFromHeader(httpRequest,
Constants.ROUTER_ID_HEADER_KEY);
AppactiveConstants.ROUTER_ID_HEADER_KEY);
if (StringUtils.isBlank(routerId)) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
"no routerId provided for this request");

@ -26,7 +26,7 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.cloud.appactive.constant.Constants;
import com.alibaba.cloud.appactive.constant.AppactiveConstants;
import io.appactive.java.api.base.AppContextClient;
import io.appactive.java.api.bridge.servlet.ServletService;
import io.appactive.java.api.rule.machine.AbstractMachineUnitRuleService;
@ -60,7 +60,7 @@ public class GlobalServiceFilter implements Filter {
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String routerId = ServletService.getRouteIdFromHeader(httpRequest,
Constants.ROUTER_ID_HEADER_KEY);
AppactiveConstants.ROUTER_ID_HEADER_KEY);
if (StringUtils.isNotBlank(routerId)) {
AppContextClient.setUnitContext(routerId);
}

@ -31,7 +31,7 @@ import org.springframework.context.annotation.Configuration;
* @author mageekchiu
*/
@Configuration
public class NacosAutoConfig {
public class ProviderAutoConfig {
@Autowired
private List<FilterRegistrationBean<? extends Filter>> beanList;

@ -24,8 +24,9 @@ import java.util.List;
import javax.servlet.Filter;
import com.alibaba.cloud.appactive.common.ServiceMeta;
import com.alibaba.cloud.appactive.common.ServiceMetaEntity;
import com.alibaba.cloud.appactive.common.ServiceMetaObject;
import com.alibaba.cloud.appactive.consumer.ServerMeta;
import com.alibaba.fastjson.JSON;
import io.appactive.java.api.base.constants.ResourceActiveType;
import io.appactive.support.lang.CollectionUtils;
@ -52,7 +53,7 @@ public final class URIRegister {
if (CollectionUtils.isEmpty(beanList)) {
return;
}
List<ServiceMeta> serviceMetaList = new LinkedList<>();
List<ServiceMetaEntity> serviceMetaList = new LinkedList<>();
boolean hasWildChar = false;
for (FilterRegistrationBean<? extends Filter> filterRegistrationBean : beanList) {
Filter filter = filterRegistrationBean.getFilter();
@ -85,10 +86,10 @@ public final class URIRegister {
}
/**
* Initialize {@link #serviceMetaObject} based on {@link ServiceMeta} list.
* Initialize {@link #serviceMetaObject} based on {@link ServerMeta} list.
* @param serviceMetaList list needed for initialization
*/
private static void initServiceMetaObject(List<ServiceMeta> serviceMetaList) {
private static void initServiceMetaObject(List<ServiceMetaEntity> serviceMetaList) {
serviceMetaObject = new ServiceMetaObject();
Collections.sort(serviceMetaList);
serviceMetaObject.setServiceMetaList(serviceMetaList);
@ -99,16 +100,17 @@ public final class URIRegister {
}
/**
* Collect {@link ServiceMeta} into the given <i>serviceMetaList</i> according to each
* item of the given <i>urlPatterns</i> and the given <i>resourceActiveType</i>,
* finally determine whether <i>hasWildChar</i> is a new wildChar.
* Collect {@link ServiceMetaEntity} into the given <i>serviceMetaList</i> according
* to each item of the given <i>urlPatterns</i> and the given
* <i>resourceActiveType</i>, finally determine whether <i>hasWildChar</i> is a new
* wildChar.
* @param serviceMetaList extended list
* @param hasWildChar keyword to be determined
* @param urlPatterns looped list
* @param resourceActiveType attribute of {@link ServiceMeta}
* @param resourceActiveType attribute of {@link ServerMeta}
* @return is new wildChar
*/
private static boolean collectServiceMetas(List<ServiceMeta> serviceMetaList,
private static boolean collectServiceMetas(List<ServiceMetaEntity> serviceMetaList,
boolean hasWildChar, Collection<String> urlPatterns,
String resourceActiveType) {
for (String urlPattern : urlPatterns) {
@ -121,16 +123,17 @@ public final class URIRegister {
}
/**
* Collect {@link ServiceMeta} into the given <i>serviceMetaList</i> according to the
* given <i>urlPattern</i> and the given <i>resourceActiveType</i>.
* Collect {@link ServiceMetaEntity} into the given <i>serviceMetaList</i> according
* to the given <i>urlPattern</i> and the given <i>resourceActiveType</i>.
* @param serviceMetaList extended list
* @param urlPattern attribute of {@link ServiceMeta}
* @param resourceActiveType attribute of {@link ServiceMeta}
* @param urlPattern attribute of {@link ServiceMetaEntity}
* @param resourceActiveType attribute of {@link ServiceMetaEntity}
*/
private static void collectServiceMeta(List<ServiceMeta> serviceMetaList,
private static void collectServiceMeta(List<ServiceMetaEntity> serviceMetaList,
String urlPattern, String resourceActiveType) {
ServiceMeta serviceMeta = new ServiceMeta(urlPattern, resourceActiveType);
serviceMetaList.add(serviceMeta);
ServiceMetaEntity serviceMetaEntity = new ServiceMetaEntity(urlPattern,
resourceActiveType);
serviceMetaList.add(serviceMetaEntity);
}
public static ServiceMetaObject getServiceMetaObject() {

@ -1,5 +1,5 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.cloud.appactive.provider.NacosAutoConfig,\
com.alibaba.cloud.appactive.provider.ProviderAutoConfig,\
com.alibaba.cloud.appactive.consumer.ConsumerAutoConfig,\
com.alibaba.cloud.appactive.config.FilterPropertiesAutoConfiguration,\
com.alibaba.cloud.appactive.config.FilterAutoConfiguration
Loading…
Cancel
Save