Skip to content

Commit

Permalink
Optimize the Appactive module (#3107)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuluo-yx authored Feb 7, 2023
1 parent 5593d67 commit a2d91e5
Show file tree
Hide file tree
Showing 17 changed files with 210 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@
* @author raozihao, mageekchiu
* @author <a href="mailto:[email protected]">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;
}
Expand All @@ -56,7 +56,7 @@ public String toString() {
}

@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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
*/
public class ServiceMetaObject {

private List<ServiceMeta> serviceMetaList;
private List<ServiceMetaEntity> serviceMetaList;

/**
* string of serviceMetaList.
Expand All @@ -33,19 +33,19 @@ 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;
}

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;
}

Expand All @@ -67,7 +67,7 @@ public void setMeta(String meta) {

@Override
public String toString() {
return "ServiceMetaObject{" + "serviceMetaList=" + serviceMetaList
return "ServiceMetaObject{" + "ServiceMetaEntityList=" + serviceMetaList
+ ", md5OfList='" + md5OfList + '\'' + '}';
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,29 @@
* @author raozihao, mageekchiu
* @author <a href="mailto:[email protected]">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() {
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
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;
Expand Down Expand Up @@ -81,10 +81,10 @@ public boolean apply(PredicateKey predicateKey) {
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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -38,8 +32,6 @@
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
Expand All @@ -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;
Expand All @@ -67,29 +56,27 @@ public Decoder appActiveFeignDecoder() {
}

@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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public Object postProcessAfterInitialization(Object bean, String beanName)
}
Decoder decoder = (Decoder) bean;
// wrap original decoder
return new ResponseInterceptor(decoder);
return new FeignResponseDecoderInterceptor(decoder);

/// another way
// Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@
* @author raozihao, mageekchiu
* @author <a href="mailto:[email protected]">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;
}
Expand All @@ -46,7 +46,7 @@ public ResponseInterceptor(Decoder delegate) {
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
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;
Expand All @@ -31,7 +31,7 @@
* @author raozihao, mageekchiu
* @author <a href="mailto:[email protected]">Steve</a>
*/
public class RouterIdTransmissionRequestInterceptor implements RequestInterceptor {
public class FeignRouterIdTransmissionRequestInterceptor implements RequestInterceptor {

@Override
public void apply(RequestTemplate requestTemplate) {
Expand All @@ -44,7 +44,7 @@ public void apply(RequestTemplate requestTemplate) {
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());
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
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;
Expand All @@ -33,21 +33,21 @@
* @author raozihao, mageekchiu
* @author <a href="mailto:[email protected]">Steve</a>
*/
public class ReqResInterceptor implements ClientHttpRequestInterceptor {
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

private static final Logger logger = LogUtil.getLogger();

@Override
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;
Expand Down
Loading

0 comments on commit a2d91e5

Please sign in to comment.