springcloudgateway 集成 Cat

前提:项目集成了 springsecurity,springdataredis

1、pom部分:


            com.dianping.cat
            cat-client
            3.0.0

2、代码部分:

package com.vsulv.bgb.modules.filter;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class CatFilter implements WebFilter , Ordered {
    private static final String START_TIME = "catStartTime";

    public static void newCompletedTransactionWithDuration(String type, String name, long duration) {
        final Transaction transaction = Cat.getProducer().newTransaction(type, name);
        try {
            transaction.setDurationInMillis(duration);
            if (duration > 0 && duration < 60 * 1000) {
                transaction.setTimestamp(System.currentTimeMillis() - duration);
            }
            transaction.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            transaction.setStatus(e);
            throw e;
        } finally {
            transaction.complete();
        }
    }
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then( Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                Long executeTime = (System.currentTimeMillis() - startTime);
                log.debug("CAT记录耗时:{}",executeTime);
                newCompletedTransactionWithDuration("URL",exchange.getRequest().getURI().getRawPath(),(executeTime));
            }
        }));
    }
}

因为原有AOP切面失效,使用filter方式拦截,并记录访问日志。

你可能感兴趣的:(集成cat)