Browse Source

版本框架更新,POM文件结构优化

hill9868 6 years ago
parent
commit
bc86314834

+ 47 - 0
commons-cat/pom.xml

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>commons</artifactId>
        <groupId>com.yihu.ehr</groupId>
        <version>1.13.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>commons-cat</artifactId>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>com.dianping.cat</groupId>
            <artifactId>cat-client</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-okhttp</artifactId>
            <version>9.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>
</project>

+ 26 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/CatContext.java

@ -0,0 +1,26 @@
package com.yihu.ehr.cat;
import com.dianping.cat.Cat;
import java.util.HashMap;
import java.util.Map;
/**
 * Context - CAT上下文
 * Created by progr1mmer on 2018/9/4.
 */
public class CatContext implements Cat.Context {
    private Map<String, String> properties = new HashMap<>();
    @Override
    public void addProperty(String key, String value) {
        properties.put(key, value);
    }
    @Override
    public String getProperty(String key) {
        return properties.get(key);
    }
}

+ 16 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/CatErrorConstants.java

@ -0,0 +1,16 @@
package com.yihu.ehr.cat;
/**
 * Constants - 常量
 * Created by progr1mmer on 2018/9/5.
 */
public class CatErrorConstants {
    /*
     * 异常在过滤链中被捕获的时候可以通过
     * request.setAttribute(ERROR_FOR_CAT, e)
     * 将异常传递给 Transaction
     */
    public static final String ERROR_FOR_CAT = "EFC";
}

+ 62 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/CatHeaderRequestWrapper.java

@ -0,0 +1,62 @@
package com.yihu.ehr.cat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
/**
 * Wrapper - 添加请求头
 * Created by progr1mmer on 2018/9/4.
 */
public class CatHeaderRequestWrapper extends HttpServletRequestWrapper {
    private final Map<String, String> customHeaders;
    CatHeaderRequestWrapper(HttpServletRequest request) {
        super(request);
        this.customHeaders = new HashMap<>();
    }
    void putHeader(String name, String value) {
        this.customHeaders.put(name, value);
    }
    @Override
    public String getHeader(String name) {
        // check the custom headers first
        String headerValue = customHeaders.get(name);
        if (headerValue != null){
            return headerValue;
        }
        // else return from into the original wrapped object
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }
    @Override
    public Enumeration<String> getHeaders(String name) {
        if (customHeaders.containsKey(name)) {
            Set<String> set = new HashSet<>();
            set.add(getHeader(name));
            return Collections.enumeration(set);
        }
        return super.getHeaders(name);
    }
    @Override
    public Enumeration<String> getHeaderNames() {
        // create a set of the custom header names
        Set<String> set = new HashSet<>(customHeaders.keySet());
        // now add the headers from the wrapped request object
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            // add the names of the request headers into the list
            String n = e.nextElement();
            set.add(n);
        }
        // create an enumeration from the set and return
        return Collections.enumeration(set);
    }
}

+ 45 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/CatOkHttpInterceptor.java

@ -0,0 +1,45 @@
package com.yihu.ehr.cat;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Transaction;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
/**
 * Interceptor - 拦截http调用过程
 * Created by progr1mmer on 2018/9/5.
 */
public class CatOkHttpInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, request.url().toString());
        try {
            //保存和传递CAT调用链上下文
            CatContext ctx = new CatContext();
            Cat.logRemoteCallClient(ctx);
            Request.Builder builder = request.newBuilder();
            builder.header(Cat.Context.ROOT, ctx.getProperty(Cat.Context.ROOT));
            builder.header(Cat.Context.PARENT, ctx.getProperty(Cat.Context.PARENT));
            builder.header(Cat.Context.CHILD, ctx.getProperty(Cat.Context.CHILD));
            request = builder.build();
            //执行请求
            Response response = chain.proceed(request);
            t.setStatus(Transaction.SUCCESS);
            return response;
        } catch (Exception e) {
            //记录异常
            t.setStatus(e);
            Cat.getProducer().logError(e);
            throw e;
        } finally {
            //当前Transaction须完成
            t.complete();
        }
    }
}

+ 108 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/CatServletFilter.java

@ -0,0 +1,108 @@
package com.yihu.ehr.cat;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Transaction;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * http://tx.cat.weimob.com/cat/doc.html - 部分说明文档
 * Filter - Cat基础过滤器
 * Created by progr1mmer on 2018/9/4.
 */
public class CatServletFilter implements Filter {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        CatHeaderRequestWrapper headerRequestWrapper = new CatHeaderRequestWrapper(request);
        if (isRoot(request)) {
            Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, request.getRequestURL().toString());
            try {
                Cat.logEvent("Request.remoteHost", request.getRemoteHost());
                Cat.logEvent("Request.params", objectMapper.writeValueAsString(request.getParameterMap()));
                CatContext catContext = new CatContext();
                Cat.logRemoteCallClient(catContext);
                headerRequestWrapper.putHeader(Cat.Context.ROOT, catContext.getProperty(Cat.Context.ROOT));
                headerRequestWrapper.putHeader(Cat.Context.PARENT, catContext.getProperty(Cat.Context.PARENT));
                headerRequestWrapper.putHeader(Cat.Context.CHILD, catContext.getProperty(Cat.Context.CHILD));
                filterChain.doFilter(headerRequestWrapper, servletResponse);
                if (null == request.getAttribute(CatErrorConstants.ERROR_FOR_CAT)) {
                    Integer status = ((HttpServletResponse) servletResponse).getStatus();
                    if (status != 500) {
                        t.setStatus(Transaction.SUCCESS);
                    } else {
                        Cat.logError(new IllegalStateException(status.toString()));
                        t.setStatus(new IllegalStateException(status.toString()));
                    }
                } else {
                    Cat.logError((Exception)request.getAttribute(CatErrorConstants.ERROR_FOR_CAT));
                    t.setStatus((Exception)request.getAttribute(CatErrorConstants.ERROR_FOR_CAT));
                }
            } catch (Exception e) {
                Cat.logError(e);
                t.setStatus(e);
                throw e;
            } finally {
                t.complete();
            }
        } else {
            CatContext catContext = new CatContext();
            catContext.addProperty(Cat.Context.ROOT, request.getHeader(Cat.Context.ROOT));
            catContext.addProperty(Cat.Context.PARENT, request.getHeader(Cat.Context.PARENT));
            catContext.addProperty(Cat.Context.CHILD, request.getHeader(Cat.Context.CHILD));
            Cat.logRemoteCallServer(catContext);
            Transaction t = Cat.newTransaction(CatConstants.TYPE_SERVICE, request.getRequestURL().toString());
            try {
                Cat.logEvent("Request.params", objectMapper.writeValueAsString(request.getParameterMap()));
                filterChain.doFilter(headerRequestWrapper, servletResponse);
                if (null == request.getAttribute(CatErrorConstants.ERROR_FOR_CAT)) {
                    Integer status = ((HttpServletResponse) servletResponse).getStatus();
                    if (status != 500) {
                        t.setStatus(Transaction.SUCCESS);
                    } else {
                        Cat.logError(new IllegalStateException(status.toString()));
                        t.setStatus(new IllegalStateException(status.toString()));
                    }
                } else {
                    Cat.logError((Exception)request.getAttribute(CatErrorConstants.ERROR_FOR_CAT));
                    t.setStatus((Exception)request.getAttribute(CatErrorConstants.ERROR_FOR_CAT));
                }
            } catch (Exception e) {
                Cat.logError(e);
                t.setStatus(e);
                throw e;
            } finally {
                t.complete();
            }
        }
    }
    @Override
    public void destroy() {
    }
    private boolean isRoot(HttpServletRequest request) {
        /*return request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID) != null &&
                request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID) != null &&
                request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID) != null;*/
        return request.getHeader(Cat.Context.ROOT) == null &&
                request.getHeader(Cat.Context.PARENT) == null &&
                request.getHeader(Cat.Context.CHILD) == null;
    }
}

+ 26 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/config/CatFilterConfig.java

@ -0,0 +1,26 @@
package com.yihu.ehr.cat.config;
import com.yihu.ehr.cat.CatServletFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * Config - 配置CAT过滤路径
 * Created by progr1mmer on 2018/9/4.
 */
@Configuration
public class CatFilterConfig {
    @Bean
    public FilterRegistrationBean catFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        CatServletFilter filter = new CatServletFilter();
        registration.setFilter(filter);
        registration.addUrlPatterns("/*");
        registration.setName("catFilter");
        registration.setOrder(1);
        return registration;
    }
}

+ 34 - 0
commons-cat/src/main/java/com/yihu/ehr/cat/config/FeignOkHttpConfig.java

@ -0,0 +1,34 @@
package com.yihu.ehr.cat.config;
import com.yihu.ehr.cat.CatOkHttpInterceptor;
import feign.Feign;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.netflix.feign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
/**
 * Config - 自定义OkHttpClient,添加拦截器
 * Created by progr1mmer on 2018/9/5.
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignOkHttpConfig {
    @Bean
    public okhttp3.OkHttpClient okHttpClient(){
        return new okhttp3.OkHttpClient.Builder()
                .readTimeout(10000, TimeUnit.SECONDS)
                .connectTimeout(10000, TimeUnit.SECONDS)
                .writeTimeout(10000, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool())
                .addInterceptor(new CatOkHttpInterceptor())
                .build();
    }
}

+ 1 - 0
commons-cat/src/main/resources/META-INF/app.properties

@ -0,0 +1 @@
app.name=commons-cat