近端包的编写

package nearclient.api;

import bdemo.common.service.facade.request.channel.ComponentDTO;
import bdemo.common.service.facade.request.channel.ComponnetConfigQueryReuqest;
import bdemo.common.service.facade.request.channel.PageDTO;
import bdemo.common.service.facade.request.channel.PageQueryRequest;
import nearclient.request.PageConfigQueryReuqest;
import nearclient.result.ApiResult;
import nearclient.service.ComponentConfigService;
import nearclient.service.PageConfigService;
import nearclient.template.OperateCallback;
import nearclient.template.OperateTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SiteServiceClient {

    @Autowired
    private OperateTemplateService operateTemplateService;

    @Autowired
    private PageConfigService pageConfigService;

    @Autowired
    private ComponentConfigService componentConfigService;


    public ApiResult<PageDTO> queryPageConfig(PageQueryRequest pageConfigQueryReuqest){
        ApiResult<PageDTO> result=new ApiResult<>();

        return operateTemplateService.operate("SiteServiceClient#queryPageConfig", result, pageConfigQueryReuqest, new OperateCallback() {
            @Override
            public void execute() {
                ApiResult<PageDTO> pageDTOApiResult= pageConfigService.queryPageConfigByPageCode(pageConfigQueryReuqest);
                if(Objects.nonNull(pageDTOApiResult)){
                    PageDTO pageDTO=pageDTOApiResult.getValue();
                    if(!CollectionUtils.isEmpty(pageDTO.getComponentIdList())){
                        ComponnetConfigQueryReuqest componnetConfigQueryReuqest=new ComponnetConfigQueryReuqest();
                        componnetConfigQueryReuqest.setComponentIdList(pageDTO.getComponentIdList());
                        ApiResult<List<ComponentDTO>> apiResult=  componentConfigService.queryComponentConfig(componnetConfigQueryReuqest);
                        Map<String,ComponentDTO> componentDTOMap=apiResult.getValue().stream().collect(Collectors.toMap(ComponentDTO::getComponentId, Function.identity()));
                        pageDTO.getComponentIdList().forEach(componentId->{
                            if(Objects.nonNull(componentDTOMap.get(componentId))){
                                pageDTO.getComponentDTOList().add(componentDTOMap.get(componentId));
                            }
                        });
                    }
                    result.setValue(pageDTO);
                    result.setSuccess(true);
                }

            }
        });
    }
}
package nearclient.cache;


import java.io.Serializable;

public class CacheWraper<T> implements Serializable {

    private T cachedData;

    private long occurTime=System.currentTimeMillis();

    /**
     * 部分miss
     */
    private Boolean partialMiss;

    private Object cacheKey;

    public T getCachedData() {
        return cachedData;
    }

    public void setCachedData(T cachedData) {
        this.cachedData = cachedData;
    }

    public long getOccurTime() {
        return occurTime;
    }

    public void setOccurTime(long occurTime) {
        this.occurTime = occurTime;
    }

    public Boolean getPartialMiss() {
        return partialMiss;
    }

    public void setPartialMiss(Boolean partialMiss) {
        this.partialMiss = partialMiss;
    }

    public Object getCacheKey() {
        return cacheKey;
    }

    public void setCacheKey(Object cacheKey) {
        this.cacheKey = cacheKey;
    }

    public boolean miss(){
        return cachedData==null || partialMiss();
    }

    public boolean partialMiss(){
        return partialMiss!=null && partialMiss;
    }

    public CacheWraper(){

    }

    public CacheWraper(T cachedData) {
        this.cachedData = cachedData;
    }

    @Override
    public String toString() {
        return "CacheWraper{" +
                "cachedData=" + cachedData +
                ", occurTime=" + occurTime +
                ", partialMiss=" + partialMiss +
                ", cacheKey=" + cacheKey +
                '}';
    }
}
package nearclient.cache;

import nearclient.enums.ErrorCodeEnums;
import nearclient.model.exception.BizException;

import java.io.Serializable;
import java.util.List;

public class CommonRedisClient {

    // jedis查询
    public Serializable get(Serializable cacheKey){

        if(cacheKey==null){
            throw new BizException(ErrorCodeEnums.ILLEGAL_PARAMS);
        }
        return null;
    }

    public List<DataEntry> batchget(List<? extends Object> cacheKeyList){

        return null;
    }


}
package nearclient.cache;

import bdemo.common.service.facade.request.channel.ComponentCacheDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class ComponentCacheQueryService {

    @Autowired
    private CommonRedisClient commonRedisClient;

    public CacheWraper<List<ComponentCacheDTO>> queryComponentConfigList(List<String> componentIdlIst){
        List<String> cacheKeyList=null;
        CacheWraper<List<ComponentCacheDTO>> cacheWraperResult=null;
        try {
            List<DataEntry> hitComponentCacheDTOList=commonRedisClient.batchget(cacheKeyList);
            List<ComponentCacheDTO> componentCacheDTOS=new ArrayList<>();
            if (!CollectionUtils.isEmpty(hitComponentCacheDTOList)){
                for (DataEntry dataEntry:hitComponentCacheDTOList){
                    ComponentCacheDTO componentCacheDTO=(ComponentCacheDTO)dataEntry.getValue();
                    if(componentCacheDTO!=null){
                        componentCacheDTOS.add(componentCacheDTO);
                    }
                }
            }
            cacheWraperResult.setPartialMiss(componentCacheDTOS.size()!=componentIdlIst.size());
        }catch (Exception e){

        }
        return cacheWraperResult;
    }
}
package nearclient.cache;

public class DataEntry {

    private Object value;

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }
}
package nearclient.cache;

import bdemo.common.service.facade.request.channel.PageCacheDTO;
import bdemo.common.service.facade.request.channel.PageDTO;
import bdemo.common.service.facade.request.channel.PageQueryRequest;
import nearclient.request.PageConfigQueryReuqest;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

public class PageCacheQueryService {

    @Autowired
    private CommonRedisClient commonRedisClient;


    public CacheWraper<PageDTO> queryPageConfigByPageCode(PageQueryRequest pageConfigQueryReuqest){
        String cacheKey=null;
        CacheWraper<PageDTO> cacheWraper=null;
        try{
            Serializable serializable=commonRedisClient.get(cacheKey);
            if(serializable!=null){
                PageCacheDTO pageCacheDTO=(PageCacheDTO)serializable;
                cacheWraper=new CacheWraper<>();
                cacheWraper.setCachedData(PageUtil.pageCacheDToConvertToDTO(pageCacheDTO));
                cacheWraper.setCacheKey(cacheKey);
            }
        }catch (Exception e){

        }
        return cacheWraper;
    }
}
package nearclient.cache;

import bdemo.common.service.facade.request.channel.PageCacheDTO;
import bdemo.common.service.facade.request.channel.PageDTO;

public class PageUtil {
    public static PageDTO pageCacheDToConvertToDTO(PageCacheDTO pageCacheDTO){
        return null;
    }
}
package nearclient.context;


import nearclient.cache.CacheWraper;
import nearclient.request.BaseClientRequest;
import nearclient.result.ApiResult;

import java.util.Date;

public class ClientRuntimeContext {

    private static final String MISS_CACHE="M";

    private static final String PARTIAL_MISS_CACHE="PM";

    private static final String NOT_MISS_CACHE="NM";

    private String bizName;

    private BaseClientRequest request;

    private ApiResult apiResult;

    private Date requestAt;

    private Date responseAt;

    private CacheWraper cacheWraper;

    private Boolean useCache;

    private Boolean useSwitch;

    private Boolean miss=false;

    public String getBizName() {
        return bizName;
    }

    public void setBizName(String bizName) {
        this.bizName = bizName;
    }

    public BaseClientRequest getRequest() {
        return request;
    }

    public void setRequest(BaseClientRequest request) {
        this.request = request;
    }

    public ApiResult getApiResult() {
        return apiResult;
    }

    public void setApiResult(ApiResult apiResult) {
        this.apiResult = apiResult;
    }

    public Date getRequestAt() {
        return requestAt;
    }

    public void setRequestAt(Date requestAt) {
        this.requestAt = requestAt;
    }

    public Date getResponseAt() {
        return responseAt;
    }

    public void setResponseAt(Date responseAt) {
        this.responseAt = responseAt;
    }

    public CacheWraper getCacheWraper() {
        return cacheWraper;
    }

    public void setCacheWraper(CacheWraper cacheWraper) {
        this.cacheWraper = cacheWraper;
    }

    public Boolean getUseCache() {
        return useCache;
    }

    public void setUseCache(Boolean useCache) {
        this.useCache = useCache;
    }

    public Boolean getUseSwitch() {
        return useSwitch;
    }

    public void setUseSwitch(Boolean useSwitch) {
        this.useSwitch = useSwitch;
    }

    public Boolean getMiss() {
        return miss;
    }

    public void setMiss(Boolean miss) {
        this.miss = miss;
    }

    public String toDigestLog(){
        return String.format("%s,%s,%s,%sms,%s,%s,%s,%s",
                bizName,
                apiResult==null?"-":(apiResult.isSuccess()?"Y":"N"),
                apiResult==null?"-":apiResult.getErrorCode(),
                responseAt.getTime()-requestAt.getTime(),
                getMissFlag(),
                getCacheKey(),
                getEmptyCache()
                );
    }

    public String toClientFullLog(){
        return String.format("[%s]成功调用 %s,方法请求参数:%s,结果 %s,耗时%sms",
                bizName,request,apiResult,responseAt.getTime()-requestAt.getTime());
    }

    private String getMissFlag(){
        if(cacheWraper==null){
            return MISS_CACHE;
        }
        if(cacheWraper.partialMiss()){
            return PARTIAL_MISS_CACHE;
        }
        if(cacheWraper.miss()){
            return MISS_CACHE;
        }
        return NOT_MISS_CACHE;
    }

    private String getCacheKey(){
        if(cacheWraper==null||cacheWraper.getCacheKey()==null){
            return "-";
        }
        return cacheWraper.getCacheKey().toString();
    }

    private String getEmptyCache(){
        if(cacheWraper==null){
            return "-";
        }
        return "N";
    }
}
package nearclient.context;

import org.springframework.beans.PropertyValue;

import java.util.List;

public class CommonBean {

    private String beanName;

    private  Class<?> beanClass;

    private String initMethod;

    private List<PropertyValue> propertyValues;


    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public Class<?> getBeanClass() {
        return beanClass;
    }

    public void setBeanClass(Class<?> beanClass) {
        this.beanClass = beanClass;
    }

    public String getInitMethod() {
        return initMethod;
    }

    public void setInitMethod(String initMethod) {
        this.initMethod = initMethod;
    }

    public List<PropertyValue> getPropertyValues() {
        return propertyValues;
    }

    public void setPropertyValues(List<PropertyValue> propertyValues) {
        this.propertyValues = propertyValues;
    }

    public CommonBean(String beanName, Class<?> beanClass) {
        this.beanName = beanName;
        this.beanClass = beanClass;
    }

    public CommonBean(String beanName, Class<?> beanClass, String initMethod) {
        this.beanName = beanName;
        this.beanClass = beanClass;
        this.initMethod = initMethod;
    }

    public CommonBean(String beanName, Class<?> beanClass, String initMethod, List<PropertyValue> propertyValues) {
        this.beanName = beanName;
        this.beanClass = beanClass;
        this.initMethod = initMethod;
        this.propertyValues = propertyValues;
    }

    public CommonBean(){}
}
package nearclient.context;

public class Properties {

    private static String appName;

    private static String env;

    private static String rpcVersion;

    public static String getAppName() {
        return appName;
    }

    public static void setAppName(String appName) {
        Properties.appName = appName;
    }

    public static String getEnv() {
        return env;
    }

    public static void setEnv(String env) {
        Properties.env = env;
    }

    public static String getRpcVersion() {
        return rpcVersion;
    }

    public static void setRpcVersion(String rpcVersion) {
        Properties.rpcVersion = rpcVersion;
    }
}
package nearclient.context;

public class RpcBean extends CommonBean {

    private String version;

    public RpcBean(String beanName, Class<?> beanClass, String version) {
        super(beanName, beanClass);
        this.version = version;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}
package nearclient.context;

import nearclient.api.SiteServiceClient;
import nearclient.cache.ComponentCacheQueryService;
import nearclient.cache.PageCacheQueryService;
import nearclient.facade.PageQueryFacade;
import nearclient.service.PageConfigService;
import nearclient.template.OperateTemplateService;
import nearclient.util.ClientLogger;
import org.apache.commons.lang.StringUtils;
import org.omg.SendingContext.RunTime;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class ServiceContext implements BeanFactoryPostProcessor {


    private DefaultListableBeanFactory factory;

    private AtomicBoolean startInited=new AtomicBoolean(false);

    private List<CommonBean> beanList=new ArrayList<>();

    private List<RpcBean> rpcBeanList=new ArrayList<>();

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        if(!startInited.compareAndSet(false,true)){
            return;
        }

        if(StringUtils.isBlank(Properties.getEnv())){
            throw new RuntimeException("env is blank");
        }

        this.factory=(DefaultListableBeanFactory)configurableListableBeanFactory;

        registerClientBean();

        regiesterRpcbean();

    }

    private void registerClientBean() {
        final String version=Properties.getRpcVersion();

        rpcBeanList.add(new RpcBean("pageQueryFacade", PageQueryFacade.class,version));


        beanList.add(new CommonBean("clientLogger", ClientLogger.class));

        beanList.add(new CommonBean("pageCacheQuerservice", PageCacheQueryService.class));

        beanList.add(new CommonBean("componentCacheQueryService", ComponentCacheQueryService.class));

        beanList.add(new CommonBean("siteServiceClient", SiteServiceClient.class));

        beanList.add(new CommonBean("operateTemplateService", OperateTemplateService.class));

        beanList.add(new CommonBean("pageConfigService", PageConfigService.class));

        beanList.add(new CommonBean("pageConfigService", PageConfigService.class));



        if(beanList==null||beanList.isEmpty()){
            return;
        }
        for (CommonBean commonBean:beanList){
            if(!factory.containsBean(commonBean.getBeanName())){
                MutablePropertyValues mutablePropertyValues=new MutablePropertyValues(commonBean.getPropertyValues());
                regiisterBean(commonBean.getBeanName(),commonBean.getBeanClass(),commonBean.getInitMethod(),mutablePropertyValues);
            }
        }
    }

    private void regiesterRpcbean(){
        if(rpcBeanList==null||rpcBeanList.isEmpty()){
            return;
        }
        for (RpcBean rpcBean:rpcBeanList){
            if(!factory.containsBean(rpcBean.getBeanName())){
                Object bean=getRpcBean(rpcBean.getBeanClass(),rpcBean.getVersion());
                factory.registerSingleton(rpcBean.getBeanName(),bean);
            }
        }
    }

    private Object getRpcBean(Class<?> aClass,String version){
//        RpcSpringConsumeBean rpcSpringConsumeBean=new RpcSpringConsumeBean();
//        rpcSpringConsumeBean.setInterfaceName(aClass.getCanonicalName());
//        rpcSpringConsumeBean.setVersion(version);
//        rpcSpringConsumeBean.initMethod();
//        return rpcSpringConsumeBean.getObject();
        return null;
    }


    private void regiisterBean(String beanName,Class<?> bean,String initMethod,MutablePropertyValues propertyValues){
        RootBeanDefinition bd=new RootBeanDefinition(bean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME,true);
        bd.setDependencyCheck(AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
        if(propertyValues!=null&& !propertyValues.isEmpty()){
            bd.setPropertyValues(propertyValues);
        }
        if(StringUtils.isNotBlank(initMethod)){
            bd.setInitMethodName(initMethod);
        }
        factory.registerBeanDefinition(beanName,bd);
    }

    public void setRpcVersion(String version){
        Properties.setRpcVersion(version);
    }

    public void setEnv(String env){
        Properties.setEnv(env);
    }
}
package nearclient.enums;


import org.apache.commons.lang.StringUtils;

public enum  ErrorCodeEnums {

     SYSTEM_EXCEPTION("SYSTEM_EXCEPTION","系统错误"),

    ILLEGAL_PARAMS("ILLEGAL_PARAMS","参数错误"),

    RPC_PAGE_EXCEPTION("RPC_PAGE_EXCEPTION","调用远端失败"),

    ;
    private String errorCode;

    private String errorMsg;

    ErrorCodeEnums(String errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public static ErrorCodeEnums getErrorCodeEnumByCode(String errorCode){
        for (ErrorCodeEnums errorCodeEnum:values()){
            if(StringUtils.equals(errorCodeEnum.getErrorCode(),errorCode)){
                return errorCodeEnum;
            }
        }
        return null;
    }
}
package nearclient.facade;

import bdemo.common.service.facade.base.CommonResponse;
import bdemo.common.service.facade.request.channel.ComponentDTO;
import bdemo.common.service.facade.request.channel.ComponentQueryRequest;
import bdemo.common.service.facade.request.channel.PageDTO;
import bdemo.common.service.facade.request.channel.PageQueryRequest;

import java.util.List;

public interface PageQueryFacade {
    CommonResponse<PageDTO> queryPageConfig(PageQueryRequest pageQueryRequest);

    CommonResponse<List<ComponentDTO>>  queryComponentInfo(ComponentQueryRequest componentQueryRequest);
}
package nearclient.model.exception;

import nearclient.enums.ErrorCodeEnums;

public class BizException extends RuntimeException {

    private String errorCode;

    private String errorMsg;

    private ErrorCodeEnums errorCodeEnums;

    public BizException() {
    }

    public BizException(ErrorCodeEnums errorCodeEnums){
        this.errorCode = errorCodeEnums.getErrorCode();
        this.errorMsg = errorCodeEnums.getErrorMsg();
        this.errorCodeEnums = errorCodeEnums;
    }
    public BizException(String errorCode, String errorMsg, ErrorCodeEnums errorCodeEnums) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.errorCodeEnums = errorCodeEnums;
    }

    public BizException(String message, String errorCode, String errorMsg, ErrorCodeEnums errorCodeEnums) {
        super(message);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.errorCodeEnums = errorCodeEnums;
    }

    public BizException(String message, Throwable cause, String errorCode, String errorMsg, ErrorCodeEnums errorCodeEnums) {
        super(message, cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.errorCodeEnums = errorCodeEnums;
    }

    public BizException(Throwable cause, String errorCode, String errorMsg, ErrorCodeEnums errorCodeEnums) {
        super(cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.errorCodeEnums = errorCodeEnums;
    }

    public BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, String errorCode, String errorMsg, ErrorCodeEnums errorCodeEnums) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.errorCodeEnums = errorCodeEnums;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public ErrorCodeEnums getErrorCodeEnums() {
        return errorCodeEnums;
    }

    public void setErrorCodeEnums(ErrorCodeEnums errorCodeEnums) {
        this.errorCodeEnums = errorCodeEnums;
    }
}

package nearclient.request;

import nearclient.result.ToString;

public class BaseClientRequest extends ToString {


}
package nearclient.request;


public class PageConfigQueryReuqest extends BaseClientRequest {

    private String pageCode;

    public String getPageCode() {
        return pageCode;
    }

    public void setPageCode(String pageCode) {
        this.pageCode = pageCode;
    }
}
package nearclient.result;

public class ApiResult<T> extends ToString {

    private boolean  success;

    private T value;

    private String errorCode;

    private String errorMsg;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public ApiResult(boolean success, T value) {
        this.success = success;
        this.value = value;
    }

    public ApiResult() {
    }
}
package nearclient.result;

import org.apache.commons.lang.builder.ToStringBuilder;

import java.io.Serializable;

public class ToString implements Serializable {

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
package nearclient.service;

import bdemo.common.service.facade.base.CommonResponse;
import bdemo.common.service.facade.request.channel.ComponentCacheDTO;
import bdemo.common.service.facade.request.channel.ComponentDTO;
import bdemo.common.service.facade.request.channel.ComponentQueryRequest;
import bdemo.common.service.facade.request.channel.ComponnetConfigQueryReuqest;
import nearclient.cache.CacheWraper;
import nearclient.cache.ComponentCacheQueryService;
import nearclient.facade.PageQueryFacade;
import nearclient.result.ApiResult;
import nearclient.template.AbstractServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ComponentConfigService extends AbstractServiceClient {


    @Autowired
    private ComponentCacheQueryService componentCacheQueryService;

    @Autowired
    private PageQueryFacade pageQueryFacade;


    public ApiResult<List<ComponentDTO>> queryComponentConfig(ComponnetConfigQueryReuqest componnetConfigQueryReuqest){

        return execute("ComponentConfigService#queryComponentConfig", componnetConfigQueryReuqest, new AbstractClientAction<List<ComponentDTO>>() {

            List<ComponentCacheDTO> componentCacheDTOList=new ArrayList<>();


            @Override
            public boolean checkParam() {
                return true;
            }

            @Override
            public boolean useCache() {
                return true;
            }

            @Override
            public CacheWraper<List<ComponentDTO>> getFromCache() {
                CacheWraper<List<ComponentCacheDTO>> cacheWraper=componentCacheQueryService.queryComponentConfigList(componnetConfigQueryReuqest.getComponentIdList());
                if(cacheWraper==null){
                    return null;
                }
                componentCacheDTOList=cacheWraper.getCachedData();
                return convertToComponentDTOFromCache(cacheWraper);
            }

            @Override
            public ApiResult<List<ComponentDTO>> hsfInvoke(CacheWraper<List<ComponentDTO>> cacheWraper) {

                List<String> missComponetIdList=getMissComponentIds(componentCacheDTOList,componnetConfigQueryReuqest);
                if(CollectionUtils.isEmpty(missComponetIdList)){
                    return new ApiResult(true,cacheWraper.getCachedData());
                }
                ComponentQueryRequest componentQueryRequest=new ComponentQueryRequest();
                CommonResponse<List<ComponentDTO>> commonResponse=pageQueryFacade.queryComponentInfo(componentQueryRequest);
                ApiResult<List<ComponentDTO>> apiResult=convertToApiResult(commonResponse);
                if(!apiResult.isSuccess()){
                    return apiResult;
                }
                List<ComponentDTO> componentDTOList=new ArrayList<>();
                if(!CollectionUtils.isEmpty(cacheWraper.getCachedData())){
                    componentDTOList.addAll(cacheWraper.getCachedData());
                }
                if(!CollectionUtils.isEmpty(apiResult.getValue())){
                    componentDTOList.addAll(apiResult.getValue());
                }
                apiResult.setValue(componentDTOList);
                return apiResult;
            }
        });
    }

    private List<String> getMissComponentIds(List<ComponentCacheDTO> componentCacheDTOS,ComponnetConfigQueryReuqest componnetConfigQueryReuqest){
        List<String> allComponentIdList=componnetConfigQueryReuqest.getComponentIdList();
        if(CollectionUtils.isEmpty(componentCacheDTOS)){
            return allComponentIdList;
        }
        Set<String> hitComponentIdList=componentCacheDTOS.stream().map(ComponentCacheDTO::getId).collect(Collectors.toSet());
        List<String> missComponentIds=new ArrayList<>();
        for (String componentId:allComponentIdList){
            if(!hitComponentIdList.contains(componentId)){
                missComponentIds.add(componentId);
            }
        }
        return missComponentIds;
    }


    protected <T> ApiResult<T> convertToApiResult(CommonResponse<T> commonResponse){
        ApiResult<T> apiResult=new ApiResult<>();
        apiResult.setErrorMsg(commonResponse.getErrorCode());
        apiResult.setErrorMsg(commonResponse.getErrorMsg());
        apiResult.setValue(commonResponse.getData());
        return apiResult;
    }


    public CacheWraper<List<ComponentDTO>> convertToComponentDTOFromCache(CacheWraper<List<ComponentCacheDTO>> cacheWraper){
        return null;
    }

}
package nearclient.service;

import bdemo.common.service.facade.base.CommonResponse;
import bdemo.common.service.facade.request.channel.PageDTO;
import bdemo.common.service.facade.request.channel.PageQueryRequest;
import nearclient.cache.CacheWraper;
import nearclient.cache.PageCacheQueryService;
import nearclient.facade.PageQueryFacade;
import nearclient.result.ApiResult;
import nearclient.template.AbstractServiceClient;
import org.springframework.beans.factory.annotation.Autowired;

public class PageConfigService extends AbstractServiceClient {

    @Autowired
    private PageCacheQueryService pageCacheQueryService;
    @Autowired
    private PageQueryFacade pageQueryFacade;


    public ApiResult<PageDTO> queryPageConfigByPageCode(PageQueryRequest pageQueryRequest){

        return execute("PageConfigService#queryPageConfigByPageCode", pageQueryRequest,new AbstractServiceClient.AbstractClientAction<PageDTO>(){

            @Override
            public boolean useCache() {
                return true;
            }

            @Override
            public CacheWraper<PageDTO> getFromCache() {
                CacheWraper<PageDTO> cacheWraper=pageCacheQueryService.queryPageConfigByPageCode(pageQueryRequest);
                return cacheWraper;
            }

            @Override
            public ApiResult<PageDTO> hsfInvoke(CacheWraper<PageDTO> cacheWraper) {
                CommonResponse<PageDTO> response= pageQueryFacade.queryPageConfig(null);
                return convertToApiResult(response);
            }
        });
    }

    protected <T> ApiResult<T> convertToApiResult(CommonResponse<T> commonResponse){
        ApiResult<T> apiResult=new ApiResult<>();
        apiResult.setErrorMsg(commonResponse.getErrorCode());
        apiResult.setErrorMsg(commonResponse.getErrorMsg());
        apiResult.setValue(commonResponse.getData());
        return apiResult;
    }
}
package nearclient.template;

import nearclient.cache.CacheWraper;
import nearclient.context.ClientRuntimeContext;
import nearclient.enums.ErrorCodeEnums;
import nearclient.model.exception.BizException;
import nearclient.request.BaseClientRequest;
import nearclient.result.ApiResult;
import nearclient.util.ClientLogger;
import nearclient.util.ClientLoggerUtils;

import java.util.Date;

public abstract class AbstractServiceClient {

    public interface ClientAction<T>{
        boolean checkParam();

        boolean useSwitch();

        CacheWraper<T> getFromSwitch();

        boolean useCache();

        CacheWraper<T> getFromCache();

        public ApiResult<T> hsfInvoke(CacheWraper<T> cacheWraper);

        ClientRuntimeContext getRuntimeContext();

    }

    public static abstract class AbstractClientAction<T> implements ClientAction<T>{

        private final ClientRuntimeContext runtimeContext=new ClientRuntimeContext();

        @Override
        public boolean checkParam() {
            return false;
        }

        @Override
        public boolean useSwitch() {
            return false;
        }

        @Override
        public CacheWraper<T> getFromSwitch() {
            return null;
        }

        @Override
        public boolean useCache() {
            return false;
        }

        @Override
        public CacheWraper<T> getFromCache() {
            return null;
        }

        @Override
        public abstract ApiResult<T> hsfInvoke(CacheWraper<T> cacheWraper);
        @Override
        public ClientRuntimeContext getRuntimeContext() {
            return null;
        }
    }

    protected <T> ApiResult<T> execute(String bizName, final BaseClientRequest request,ClientAction<T> action){
        ClientRuntimeContext runtimeContext=new ClientRuntimeContext();
        runtimeContext.setBizName(bizName);
        runtimeContext.setRequest(request);
        runtimeContext.setRequestAt(new Date());
        ApiResult<T> result=new ApiResult<>();
        CacheWraper<T> cacheWraper=null;
        try{
            boolean cheParamSuccess=action.checkParam();
            if(!cheParamSuccess){
                result.setSuccess(false);
                result.setErrorCode(ErrorCodeEnums.ILLEGAL_PARAMS.getErrorCode());
                result.setErrorMsg(ErrorCodeEnums.ILLEGAL_PARAMS.getErrorMsg());
                return result;
            }
            if(action.useSwitch()){
                cacheWraper=action.getFromSwitch();
                runtimeContext.setCacheWraper(cacheWraper);
                if(null!=cacheWraper){
                    result.setSuccess(true);
                    result.setValue(cacheWraper.getCachedData());
                    return result;
                }
            }

            if(action.useCache()){
                runtimeContext.setUseCache(true);
                cacheWraper=action.getFromCache();
                runtimeContext.setCacheWraper(cacheWraper);
                if(null!=cacheWraper){
                    result.setSuccess(true);
                    result.setValue(cacheWraper.getCachedData());
                    return result;
                }
            }
            runtimeContext.setMiss(true);
            result=action.hsfInvoke(cacheWraper);

            if(result!=null&& !result.isSuccess()){
                defaultAction(result,action,ErrorCodeEnums.RPC_PAGE_EXCEPTION.getErrorCode(),ErrorCodeEnums.RPC_PAGE_EXCEPTION.getErrorMsg());
            }
        }catch (BizException e){
            ClientLoggerUtils.info(ClientLogger.CLIENT_LOG,"bizName={0},request={1},errorCode={2},errorMsg={3}",
                    bizName,request,e.getErrorCode(),e.getErrorMsg());
            defaultAction(result,action,e.getErrorCode(),e.getErrorMsg());
        }catch (Exception e){
            ClientLoggerUtils.info(ClientLogger.CLIENT_LOG,"bizName={0},request={1},errorCode={2},errorMsg={3}",
                    bizName,request,ErrorCodeEnums.SYSTEM_EXCEPTION.getErrorCode(),ErrorCodeEnums.SYSTEM_EXCEPTION.getErrorMsg());
            defaultAction(result,action,ErrorCodeEnums.SYSTEM_EXCEPTION.getErrorCode(),ErrorCodeEnums.SYSTEM_EXCEPTION.getErrorMsg());

        }finally {
            printLog(runtimeContext,result,cacheWraper);
        }
        return result;
    }

    private  void printLog(ClientRuntimeContext runtimeContext, ApiResult result, CacheWraper cacheWraper) {
        runtimeContext.setApiResult(result);
        runtimeContext.setResponseAt(new Date());
        if(null!=cacheWraper){
            runtimeContext.setMiss(cacheWraper.miss());
        }
        ClientLoggerUtils.info(ClientLogger.DIGEST_LOG,runtimeContext.toDigestLog());
        ClientLoggerUtils.info(ClientLogger.CLIENT_LOG,runtimeContext.toClientFullLog());

    }


    private <T> void defaultAction(ApiResult<T> result,ClientAction<T> action,String errorCode,String errorMsg){
        try{
          CacheWraper<T> cacheWraper=action.getFromSwitch();
          if(cacheWraper!=null){
              result.setSuccess(true);
              result.setValue(cacheWraper.getCachedData());
          }
        }catch (Exception e){
            result.setSuccess(false);
            result.setErrorCode(errorCode);
            result.setErrorMsg(errorMsg);
        }
    }

}
package nearclient.template;

public interface OperateCallback {

    default void before(){}

    void execute();

    default void after(){}
}
package nearclient.template;

import nearclient.enums.ErrorCodeEnums;
import nearclient.model.exception.BizException;
import nearclient.result.ApiResult;
import nearclient.util.ClientLogger;
import nearclient.util.ClientLoggerUtils;
import org.apache.commons.lang.time.StopWatch;

public class OperateTemplateService {


    public <T,R>ApiResult operate(String bizName,ApiResult<T> response,R request,OperateCallback operateCallback){
        StopWatch stopWatch=new StopWatch();
        stopWatch.start();
        try{
            operateCallback.before();
            operateCallback.execute();
            operateCallback.after();
        }catch (BizException e){
            ClientLoggerUtils.info(ClientLogger.CLIENT_LOG,"bizName={0} request={1} errorCode={2} errmsg={3}",
                    bizName,request,e.getErrorCode(),e.getErrorMsg());
            return fail(response,e.getErrorCode(),e.getErrorMsg());
        }catch (Exception e){
            ClientLoggerUtils.info(ClientLogger.CLIENT_LOG,"bizName={0} request={1}",
                    bizName,request);
            return fail(response, ErrorCodeEnums.SYSTEM_EXCEPTION.getErrorCode(),ErrorCodeEnums.SYSTEM_EXCEPTION.getErrorMsg());
        }finally {
            stopWatch.stop();
            String digestLog=String.format("%s,%s,%s,%s,%sms",
                    bizName,response==null?ClientLoggerUtils.STRIKE:(response.isSuccess()?"Y":"N"),
                    response==null?ClientLoggerUtils.STRIKE:response.getErrorCode(),
                    stopWatch.getTime());
            ClientLoggerUtils.info(ClientLogger.CLIENT_LOG,digestLog);
        }
        return response;
    }


    private ApiResult fail(ApiResult apiResult,String errorCode,String msg){
        apiResult.setSuccess(false);
        apiResult.setErrorCode(errorCode);
        apiResult.setErrorMsg(msg);
        return apiResult;
    }
}
package nearclient.util;

import nearclient.context.Properties;
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggerRepository;
import org.springframework.beans.factory.InitializingBean;

import java.io.File;

public class ClientLogger implements InitializingBean {


    public static final Logger CLIENT_LOG=Logger.getLogger("CLIENT-LOG");

    public static final Logger DIGEST_LOG=Logger.getLogger("DIGEST-LOG");

    private final static String DATE_PATTERN="'.'yyyy-MM-dd";

    private final static String LAYOUT_PATTERN="%d [%t] - %m%n";

    private final static String CLIENT_APPENDER_NAME="CLIENT_APPENDER";

    private final static String DIGEST_APPENDER_NAME="DIGEST_APPENDER";

    private final static String CONVERSION_PATTERN="%d %-5p %m%n";

    private final static String FILE_ENCODING="UTF-8";

    private final static String ERROR_APPENDER="ERROR_APPENDER";

    private final static String CONSOLE="CONSOLE";

    private final static String CLIENT_LOG_FILE_NAME="aa-client.log";

    private final static String CLIENT_DIGEST_LOG_FILE_NAME="aa-client-digest.log";


    @Override
    public void afterPropertiesSet() throws Exception {
        PatternLayout patternLayout=new PatternLayout(LAYOUT_PATTERN);
        patternLayout.setConversionPattern(CONVERSION_PATTERN);
        String path=getLogFilePath();
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String clientLogeFileName=path+CLIENT_LOG_FILE_NAME;
        String clientLogDigestFileName=path+CLIENT_DIGEST_LOG_FILE_NAME;

        DailyRollingFileAppender clientAppender;
        DailyRollingFileAppender clientDigestAppender;

        LoggerRepository repository= LogManager.getLoggerRepository();
        DailyRollingFileAppender errorAppender=(DailyRollingFileAppender)repository.getRootLogger().getAppender(ERROR_APPENDER);
        Appender consoleAppender=repository.getRootLogger().getAppender(CONSOLE);
        try {
            clientAppender=new DailyRollingFileAppender(patternLayout,clientLogeFileName,DATE_PATTERN);
            clientAppender.setAppend(true);
            clientAppender.setEncoding(FILE_ENCODING);
            clientAppender.setName(CLIENT_APPENDER_NAME);

            clientDigestAppender=new DailyRollingFileAppender(patternLayout,clientLogDigestFileName,DATE_PATTERN);
            clientDigestAppender.setAppend(true);
            clientDigestAppender.setEncoding(FILE_ENCODING);
            clientDigestAppender.setName(DIGEST_APPENDER_NAME);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

        CLIENT_LOG.setLevel(Level.INFO);
        CLIENT_LOG.addAppender(clientAppender);
        CLIENT_LOG.addAppender(errorAppender);
        CLIENT_LOG.setAdditivity(false);

        DIGEST_LOG.setLevel(Level.INFO);
        DIGEST_LOG.addAppender(clientDigestAppender);
        DIGEST_LOG.addAppender(errorAppender);
        DIGEST_LOG.setAdditivity(false);

        if(consoleAppender!=null){
            CLIENT_LOG.addAppender(consoleAppender);
            DIGEST_LOG.addAppender(consoleAppender);
        }
        CLIENT_LOG.info("client log init");
    }

    private String getLogFilePath(){
        String userHome=System.getProperty("user.home");
        if(!userHome.endsWith(File.separator)){
            userHome+=File.separator;
        }
        return userHome+ Properties.getAppName()+File.separator+"logs"+File.separator;
    }

    public enum LogMode{
        FULL("full"),

        NONE("none"),

        SIMPLE("simple")

        ;

        LogMode(String code) {
            this.code = code;
        }

        private final String code;

        public String getCode() {
            return code;
        }
    }
}
package nearclient.util;

import org.apache.log4j.Logger;

import java.text.MessageFormat;
import java.util.UUID;

public class ClientLoggerUtils {

    public static final char LEFT_SQUARE_BRACKET='[';

    public static final char RIGHT_SQUARE_BRACKET=']';

    public static final String DEFAULT_VALUE="-";

    public static final String YES="Y";

    public static final String NO="N";
    
    public static final String STRIKE="-";
    
    public static void info(Logger logger, String message, Object...parmas){
        if(logger.isInfoEnabled()&&canLog(logger)){
            logger.info(format(message,parmas));
        }
    }

    private static String format(String message, Object...params){
        String traceId="-";
        try {
            traceId= UUID.randomUUID().toString();
            StringBuilder log=new StringBuilder();
            log.append(LEFT_SQUARE_BRACKET).append(traceId).append(RIGHT_SQUARE_BRACKET).append(LEFT_SQUARE_BRACKET).append(Thread.currentThread().getId()).append(RIGHT_SQUARE_BRACKET)
                    ;
            if(params!=null&&params.length!=0){
                log.append(MessageFormat.format(message,params));
                return log.toString();
            }else {
                log.append(message);
                return log.toString();
            }
        }catch (Exception e){
            return "print log exception traceid="+traceId+e.getMessage();
        }
    }

    private static boolean canLog(Logger logger) {
        if(LogSwitch.isLogNoneMode()){
            return false;
        }
        if(LogSwitch.isLogFullMode()){
            return true;
        }
        if(LogSwitch.isLogSimpleMode()){
            if(ClientLogger.DIGEST_LOG.equals(logger)){
                return true;
            }
            if(ClientLogger.CLIENT_LOG.equals(logger)){
                return false;
            }
        }
        return false;
    }
}
package nearclient.util;

import org.apache.commons.lang.StringUtils;

public class LogSwitch {

    public static String clientLogMode=ClientLogger.LogMode.FULL.getCode();

    public static boolean isLogFullMode(){
        return StringUtils.equals(clientLogMode,ClientLogger.LogMode.FULL.getCode());
    }

    public static boolean isLogNoneMode(){
        return StringUtils.equals(clientLogMode,ClientLogger.LogMode.NONE.getCode());

    }

    public static boolean isLogSimpleMode(){
        return StringUtils.equals(clientLogMode,ClientLogger.LogMode.SIMPLE.getCode());

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
抢票脚本是指在手机应用(app)端编写的用于自动化抢购车票的程序脚本。下面是关于如何编写抢票脚本的一些建议: 首先,需要选择合适的编程语言并确保其适用于手机应用的开发环境。常用的语言如Python、Java等,可以根据个人熟悉度和开发环境的要求选择适合的语言。 其次,需要了解目标应用的接口和交互方式。通过分析目标应用的网络请求和响应,可以获取到一些关键的信息,例如请求的URL、参数、返回的数据格式等。可以使用抓工具,如Fiddler、Charles等来获取这些信息。 然后,可以根据获取的信息编写脚本。脚本主要括以下几个步骤:登录、选定目标车次、提交订单。可以使用相关的网络请求库来发送请求,并解析返回的数据获取所需的信息。例如,可以使用Python中的requests库发送POST请求,然后根据返回数据中的车次信息进行筛选和选择。 在编写脚本时,需要注意模拟用户行为,避免过于频繁的请求,以免触发应用的反爬机制。可以设置合理的请求时间间隔,模拟人工操作的速度和方式。 最后,需要对脚本进行测试和调试,确认其功能正常。可以使用模拟数据进行测试,并逐步优化和完善脚本的代码。 需要注意的是,抢票脚本编写涉及到触碰到法律和道德的底线,尤其是在有限供应的情况下。在使用抢票脚本时,要遵守平台的使用规则,遵从规则和道德,在合法合规的前提下进行使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值