Explorar o código

添加cat模块

suxiaoyang %!s(int64=6) %!d(string=hai) anos
pai
achega
572b265380

+ 42 - 0
cat-starter/pom.xml

@ -0,0 +1,42 @@
<?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>jkzl-starter</artifactId>
        <groupId>com.yihu</groupId>
        <version>2.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cat-starter</artifactId>
    <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>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-okhttp</artifactId>
        </dependency>
    </dependencies>
</project>

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

@ -0,0 +1,26 @@
package com.yihu.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);
    }
}

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

@ -0,0 +1,62 @@
package com.yihu.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
cat-starter/src/main/java/com/yihu/cat/CatOkHttpInterceptor.java

@ -0,0 +1,45 @@
package com.yihu.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_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) {
            //记录异常
            Cat.getProducer().logError(e);
            t.setStatus(e);
            throw e;
        } finally {
            //当前Transaction须完成
            t.complete();
        }
    }
}

+ 90 - 0
cat-starter/src/main/java/com/yihu/cat/CatServletFilter.java

@ -0,0 +1,90 @@
package com.yihu.cat;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Transaction;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Filter - Cat基础过滤器
 * Created by progr1mmer on 2018/9/4.
 */
public class CatServletFilter implements Filter {
    @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_CALL, request.getRequestURL().toString());
            try {
                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);
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                if (response.getStatus() == 200) {
                    t.setStatus(Transaction.SUCCESS);
                } else {
                    t.setStatus("-1");
                }
            } catch (Exception e) {
                Cat.getProducer().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.remoteHost", request.getRemoteHost());
                filterChain.doFilter(headerRequestWrapper, servletResponse);
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                if (response.getStatus() == 200) {
                    t.setStatus(Transaction.SUCCESS);
                } else {
                    t.setStatus("-1");
                }
            } catch (Exception e) {
                t.setStatus(e);
                Cat.logError(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
cat-starter/src/main/java/com/yihu/cat/config/CatFilterConfig.java

@ -0,0 +1,26 @@
package com.yihu.cat.config;
import com.yihu.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("cat-filter");
        registration.setOrder(1);
        return registration;
    }
}

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

@ -0,0 +1,34 @@
package com.yihu.cat.config;
import com.yihu.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();
    }
}

+ 49 - 1
pom.xml

@ -27,6 +27,7 @@
        <module>elasticsearch-starter</module>
        <module>elasticsearch-transport-starter</module>
        <module>elasticsearch-jest-starter</module>
        <module>cat-starter</module>
    </modules>
    <!-- 项目发布到这个服务器 -->
@ -39,6 +40,7 @@
    </distributionManagement>
    <properties>
        <version.spring-cloud>Edgware.SR1</version.spring-cloud>
        <version.jackson>2.6.6</version.jackson>
        <version.fastdfs>1.27</version.fastdfs>
        <version.swagger>2.7.0</version.swagger>
@ -65,11 +67,22 @@
        <version.json>20160212</version.json>
        <version.json-lib>2.4</version.json-lib>
        <version.pinyin4j>2.5.0</version.pinyin4j>
        <version.cat>2.0.0</version.cat>
        <version.feign-okhttp>9.3.1</version.feign-okhttp>
    </properties>
    <dependencyManagement>
        <dependencies>
            <!-- Spring Cloud -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${version.spring-cloud}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- FastDFS library -->
            <dependency>
                <groupId>org.csource</groupId>
@ -277,7 +290,42 @@
                <version>${version.pinyin4j}</version>
            </dependency>
            <!-- Cat -->
            <dependency>
                <groupId>com.dianping.cat</groupId>
                <artifactId>cat-client</artifactId>
                <version>${version.cat}</version>
            </dependency>
            <!-- OkHttp -->
            <dependency>
                <groupId>io.github.openfeign</groupId>
                <artifactId>feign-okhttp</artifactId>
                <version>${version.feign-okhttp}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

+ 0 - 113
utils/src/main/java/com/yihu/utils/context/SpringContextHolder.java

@ -1,113 +0,0 @@
package com.yihu.utils.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * Spring上下文管理器。
 *
 * @author Sand
 * @version 1.0
 * @created 12-05-2015 17:47:55
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    @Autowired
    private static ApplicationContext springContext = null;
    /**
     * 获取Spring应用上下文环境。
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return springContext;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        springContext = applicationContext;
    }
    /**
     * 获取服务。
     *
     * @param serviceName
     * @param <T>
     * @return
     */
    public static <T> T getService(String serviceName) {
        return (T) springContext.getBean(serviceName);
    }
    public static <T> T getService(Class<T> beanCls) {
        return (T) springContext.getBean(beanCls);
    }
    /**
     * 获取服务,并用参数初始化对象。
     *
     * @param serviceName
     * @param args
     * @param <T>
     * @return
     */
    public static <T> T getService(String serviceName, Object... args) {
        T ref = (T)springContext.getBean(serviceName, args);
        if (ref == null) return null;
        return ref;
    }
    public static <T> T getService(Class<T> beanCls, Object... args){
        T ref = (T)springContext.getBean(beanCls, args);
        if (ref == null) return null;
        return ref;
    }
    /**
     * 获取平台支持的所有服务名称。
     *
     * @return
     */
    public static String[] getAvailableServiceNames() {
        String[] serviceNames = springContext.getBeanDefinitionNames();
        return serviceNames;
    }
    /**
     * 判断是否支持特定服务。
     *
     * @param serviceName
     * @return
     */
    public static boolean isServiceSupported(String serviceName) {
        return springContext.containsBeanDefinition(serviceName);
    }
    /**
     * 获取服务的实现类。
     *
     * @param serviceName
     * @return
     */
    public static Class getServiceType(String serviceName) {
        return springContext.getType(serviceName);
    }
    /**
     * 判断服务是否为单例模式。
     *
     * @param serviceName
     * @return
     */
    public static boolean isSingleton(String serviceName) {
        return springContext.isSingleton(serviceName);
    }
}