一、Cat源代碼下載和打包
1、安裝環(huán)境:
下面是本人的安裝環(huán)境
僅供參考:
1)操作系統(tǒng):win10,JDK:1.8,tomcat:8.5+, mysql:5.7,cat:3.0.0,[安裝git和maven環(huán)境鏈接](https://blog.csdn.net/tiny_du/article/details/119150481)
2)部署cat前準(zhǔn)備: 需要提前安裝好jdk1.8的環(huán)境,tomcat環(huán)境,已經(jīng)mysql環(huán)境,在此不進(jìn)行多講,有問題的伙伴可以百度自行解決。
2、在鏡像網(wǎng)站下載cat源碼和cat需要的依賴包
下載地址
cat源碼:下載master分支代碼;
cat依賴包:下載mvn-repo分支代碼;
3、在本地打cat的war包
-
首先把下載的cat源碼工程更名,改為cat;**
image -
看手冊(cè)說明,要看cat項(xiàng)目根目錄的README.md文件**
README.md說明: 1、根目錄下 cat-client 模塊以后不再維護(hù),下個(gè)大版本更新計(jì)劃移除。新版Java客戶端參考:lib/java;--操作:將cat根目錄的pom.xml中cat-client的模塊刪除(刪除<module>cat-client</module>) 2、管理端、服務(wù)端、告警服務(wù)均使用 cat-home 模塊部署即可
4、其他模塊:
integration:cat和一些第三方工具集成的內(nèi)容(此部分一部分是由社區(qū)貢獻(xiàn),一部分官方貢獻(xiàn))
lib:CAT 的客戶端,包括 Java、C/C++、Python、Node.js、Go
script:CAT 數(shù)據(jù)庫腳本
-
在cat工程執(zhí)行編譯命令
編譯命令:mvn clean compile 報(bào)錯(cuò)1:Could not find artifact org.unidal.framework:foundation-service:jar:2.5.0[ERROR] Failed to execute goal on project cat-core: Could not resolve dependencies for project com.dianping.cat:cat-core:jar:3.0.0: The following artifacts could not be resolved: org.unidal.framework:foundation-service:jar:2.5.0, org.unidal.framework:web-framework:jar:2.4.0, org.unidal.framework:dal-jdbc:jar:2.4.0: Could not find artifact org.unidal.framework:foundation-service:jar:2.5.0 in alimaven (http://maven.aliyun.com/nexus/content/groups/public) -> [Help 1] 解決:將下載的mvn-repo分支解壓,放入到本地的.m2倉庫中;本地mvn-repo分支解壓,解壓出org目錄;將org目錄拷貝到本地的.m2倉庫中; 再執(zhí)行編譯命令: 報(bào)錯(cuò)2:Failure to find org.codehaus.plexus:plexus-container-default:jar:3.1.0[ERROR] Failed to execute goal org.unidal.maven.plugins:codegen-maven-plugin:2.5.8:dal-model (generate data model) on project cat-core: Execution generate data model of goal org.unidal.maven.plugins:codegen-maven-plugin:2.5.8:dal-model failed: Plugin org.unidal.maven.plugins:codegen-maven-plugin:2.5.8 or one of its dependencies could not be resolved: Failure to find org.codehaus.plexus:plexus-container-default:jar:3.1.0 in http://maven.aliyun.com/nexus/content/groups/public was cached in the local repository, resolution will not be reattempted until the update interval of alimaven has elapsed or updates are forced -> [Help 1] 解決:在.m2倉庫找到org.unidal.maven.plugins:codegen-maven-plugin:2.5.8版本的pom文件codegen-maven-plugin-2.5.8.pom用idea打開,點(diǎn)擊父引用的default,跳轉(zhuǎn)到default-2.5.8.pom文件中,將文件中foundation-service.version從3.1.0版本修改為4.0.0版本;
<parent>
<groupId>org.unidal.maven.plugins</groupId>
<artifactId>default</artifactId>
<version>2.5.8</version>
</parent>
<foundation-service.version>4.0.0</foundation-service.version>
再執(zhí)行編譯命令:這里是JDK11版本會(huì)碰到的問題
報(bào)錯(cuò)3:程序包 sun.misc找不到符號(hào)類 BASE64Encoder
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.2:compile (default-compile) on project cat-consumer: Compilation failure: Compilation failure:[ERROR] /D:/Nikey/Project/Repository/gitee/cat/cat/cat-consumer/src/main/java/com/dianping/cat/consumer/util/InvidStringBuilder.java:[21,16] 找不到符號(hào)[ERROR] 符號(hào): 類 BASE64Encoder[ERROR] 位置: 程序包 sun.misc
解決:找到InvidStringBuilder.java這個(gè)類,將import sun.misc.BASE64Encoder; 替換為import org.apache.commons.codec.binary.Base64;將return語句,替換為return "Base64." + Base64.encodeBase64(key.getBytes());//import sun.misc.BASE64Encoder;import org.apache.commons.codec.binary.Base64;// return "Base64." + new BASE64Encoder().encodeBuffer(key.getBytes()).trim(); return "Base64." + Base64.encodeBase64(key.getBytes());
再執(zhí)行編譯命令:編譯即可成功
-
在cat根目錄執(zhí)行install命令
執(zhí)行install命令: mvn clean install -DskipTests 報(bào)錯(cuò):Could not find artifact org.unidal.framework:test-framework:jar:2.4.0 [ERROR] Failed to execute goal on project cat-core: Could not resolve dependencies for project com.dianping.cat:cat-core:jar:3.0.0: Could not find artifact org.unidal.framework:test-framework:jar:2.4.0 in alimaven(http://maven.aliyun.com/nexus/content/groups/public) -> [Help 1] 解決:修改cat根目錄的pom.xml文件中test-framework的版本,改為2.5.0 再執(zhí)行install命令: install成功后,在下面的路徑獲取到war包,將cat-home-3.0.0.war修改為cat.war或者可以直接下載war包,可以選擇適合自己的包文件進(jìn)行下載。 http://unidal.org/nexus/service/local/repositories/releases/content/com/dianping/cat/cat-home/3.0.0/

-
查看每個(gè)module具體生效的pom信息
在cat根目錄執(zhí)行命令:打開cat.txt,即可看到cat-home定義的version mvn help:effective-pom > cat.txt
二、服務(wù)端安裝和配置
1、準(zhǔn)備環(huán)境
tomcat:apache-tomcat-8.5.68
mysql:mysql5.7.22
jdk1.8
美團(tuán)cat源碼打的war包:cat.war
2、安裝CAT的數(shù)據(jù)庫
連接本地的mysql數(shù)據(jù)庫
創(chuàng)建數(shù)據(jù)庫,數(shù)據(jù)庫名cat,數(shù)據(jù)庫編碼使用utf8mb4,否則可能造成中文亂碼等問題;
CREATE SCHEMAcatDEFAULT CHARACTER SET utf8mb4 ;將cat工程中,script目錄中的sql拷貝到cat數(shù)據(jù)庫運(yùn)行
script目錄:CatApplication.sql
-
sql拷貝到cat數(shù)據(jù)庫運(yùn)行,初始化數(shù)據(jù)表;
由于MySQL的系統(tǒng)參數(shù)max_allowed_packet默認(rèn)配置較小,可能會(huì)限制server接受的數(shù)據(jù)包大小,有時(shí)候大的插入和更新會(huì)被max_allowed_packet 參數(shù)限制掉,導(dǎo)致失敗,所以要修改max_allowed_packet的值,修改后需要重啟mysql; 在mysql的安裝目錄修改配置文件(如果沒有,自己創(chuàng)建一個(gè)):C:\Program Files\MySQL\MySQL Server 5.7\my.ini [mysqld] port=3306 max_allowed_packet=1000M [client] port=3306 重啟mysql: net stop mysql net start mysql 使用MySQL Workbench工具連接本地的mysql數(shù)據(jù)庫,執(zhí)行命令: show VARIABLES like '%max_allowed_packet%';
3、Cat配置文件
在tomcat安裝的磁盤目錄,創(chuàng)建以下2個(gè)目錄,并且賦予讀寫權(quán)限;我的tomcat安裝在了D盤,所以在D盤創(chuàng)建如下2個(gè)目錄:
D:\data\appdatas\cat
D:\data\applogs\cat
在D:\data\appdatas\cat目錄中,添加client.xml,datasources.xml,server.xml配置文件
client.xml配置文件
<?xml version="1.0" encoding="utf-8"?>
<config mode="client">
<servers>
<!-- 服務(wù)端地址, 端口固定-->
<!-- 如果有多個(gè)Server, 就繼續(xù)增加相應(yīng)的節(jié)點(diǎn)配置 -->
<!-- 這是告訴客戶端應(yīng)該去鏈接哪個(gè)服務(wù)端,從哪個(gè)服務(wù)端里獲取配置信息 ,相關(guān)源碼也在 DefaultClientConfigManager中 -->
<server ip="127.0.0.1" port="2280" http-port="8080" />
</servers>
</config>
datasources.xml配置文件
<?xml version="1.0" encoding="utf-8"?>
<data-sources>
<data-source id="cat">
<maximum-pool-size>3</maximum-pool-size>
<connection-timeout>1s</connection-timeout>
<idle-timeout>10m</idle-timeout>
<statement-cache-size>1000</statement-cache-size>
<properties>
<driver>com.mysql.jdbc.Driver</driver>
<url><![CDATA[jdbc:mysql://127.0.0.1:3306/cat]]></url> <!-- 請(qǐng)?zhí)鎿Q為真實(shí)數(shù)據(jù)庫URL及Port -->
<user>root</user> <!-- 請(qǐng)?zhí)鎿Q為真實(shí)數(shù)據(jù)庫用戶名 -->
<password>root</password> <!-- 請(qǐng)?zhí)鎿Q為真實(shí)數(shù)據(jù)庫密碼 -->
<connectionProperties><![CDATA[useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&socketTimeout=120000]]></connectionProperties>
</properties>
</data-source>
</data-sources>
4、tomcat啟動(dòng)cat項(xiàng)目
將cat.war拷貝到tomcat的webapps目錄,再啟動(dòng)tomcat;
運(yùn)行命令啟動(dòng)tomcat:D:\Tool\apache-tomcat-8.5.68\bin\startup.bat
如果mysql的版本使用了8.0,啟動(dòng)tomcat后,會(huì)報(bào)錯(cuò):[ChannelManager] Error when try connecting to /127.0.0.1:2280,解決方法:安裝5.7版本的mysql就沒問題了;
啟動(dòng)成功后,訪問:http://127.0.0.1:8080/cat/r
如果遇到
5、按照實(shí)際需要,修改服務(wù)端配置和客戶端路由
使用admin/admin登錄
進(jìn)入【服務(wù)端配置】頁面修改IP地址
鏈接地址:http://127.0.0.1:8080/cat/s/config?op=serverConfigUpdate
進(jìn)入【客戶端路由】頁面修改IP地址
鏈接地址:http://127.0.0.1:8080/cat/s/config?op=routerConfigUpdate
6、瀏覽器訪問cat
瀏覽器訪問服務(wù),發(fā)現(xiàn)已經(jīng)可以正常訪問cat的頁面。不能正常啟動(dòng),檢查你的服務(wù)端文件配置主要是IP和端口配置是否正確,配置正確重新啟動(dòng)你的電腦再試試

7、配置cat
cat的默認(rèn)賬號(hào)密碼是admin/admin
初次部署后,需要對(duì)cat進(jìn)行相對(duì)應(yīng)的配置,否則打開報(bào)表頁面,全是500的報(bào)錯(cuò)提示,需要配置后才能正常顯示。


三、客戶端集成案例
編寫一個(gè)springboot與cat整合的案例
1、在pom.xml中加入cat-client 的meven依賴
<dependency>
<groupId>com.dianping.cat</groupId>
<artifactId>cat-client</artifactId>
<version>3.0.0</version>
</dependency>
***<!-- mybatis接入CAT的依賴 -->***
<dependency>
<groupId>com.dianping.cat</groupId>
<artifactId>cat-client-mybatis</artifactId>
<version>2.0.0</version>
</dependency>
2.引入核心過濾器
將CatFilterConfigure.java 放到任意SpringBoot 能掃描到的package下面
import com.dianping.cat.servlet.CatFilter;i
mport org.springframework.boot.web.servlet.FilterRegistrationBean;i
mport org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** * Description:cat的的核心過濾器
* Author: lxf
* Date: 2021/10/11
*/
@Configurationpublicclass
publicclass CatFilterConfigure {
@Bean
public FilterRegistrationBean catFilter() {
FilterRegistrationBean registration =new FilterRegistrationBean();
CatFilter filter =new CatFilter();
registration.setFilter(filter);
registration.addUrlPatterns("/*");
registration.setName("cat-filter");
registration.setOrder(1);
return registration;
}
}
3. 配置監(jiān)控項(xiàng)目名
在需要被監(jiān)聽的項(xiàng)目src/main/resources/META-INF目錄下添加配置文件app.properties

文件內(nèi)容為:
app.name=test (自己定義要和平臺(tái)定義的CMDB一致即可)
在META-INF下面創(chuàng)建client.xml文件啟動(dòng)項(xiàng)目
<?xml version="1.0" encoding="UTF-8"?><config mode="client"><domain id="test"/></config>
出現(xiàn)下面類似日志說明加載成功。

就可以看到test輸出到cat的日志:

2.mybatis集成CAT
- 引入攔截器
將CatMybatisPlugin.java 放到任意SpringBoot 能掃描到的package下面
import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;importorg.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.mybatis.spring.transaction.SpringManagedTransaction;import org.springframework.util.ReflectionUtils;
import javax.sql.DataSource;import java.lang.reflect.Field;
import java.lang.reflect.Method;import java.text.DateFormat;importjava.util.*;
import java.util.concurrent.ConcurrentHashMap;import java.util.regex.Matcher;
/** * 對(duì)MyBatis進(jìn)行攔截,添加Cat監(jiān)控
* @author Steven
*/
@Intercepts({
@Signature(method = "query", type = Executor.class, args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class}),
@Signature(method = "update", type = Executor.class, args = {MappedStatement.class, Object.class})
})publicclassCatMybatisPluginimplements Interceptor {
privatestaticLog logger = LogFactory.getLog(CatMybatisPlugin.class);
//緩存,提高性能privatestaticfinalMap sqlURLCache =newConcurrentHashMap(256);
privatestaticfinalString EMPTY_CONNECTION = "jdbc:mysql://unknown:3306/%s?useUnicode=true";
private Executor target;
// druid 數(shù)據(jù)源的類名稱privatestaticfinalString DruidDataSourceClassName = "com.alibaba.druid.pool.DruidDataSource";
// dbcp 數(shù)據(jù)源的類名稱privatestaticfinalString DBCPBasicDataSourceClassName = "org.apache.commons.dbcp.BasicDataSource";
// dbcp2 數(shù)據(jù)源的類名稱privatestaticfinalString DBCP2BasicDataSourceClassName = "org.apache.commons.dbcp2.BasicDataSource";
// c3p0 數(shù)據(jù)源的類名稱privatestaticfinalString C3P0ComboPooledDataSourceClassName = "com.mchange.v2.c3p0.ComboPooledDataSource";
// HikariCP 數(shù)據(jù)源的類名稱privatestaticfinalString HikariCPDataSourceClassName = "com.zaxxer.hikari.HikariDataSource";
// BoneCP 數(shù)據(jù)源的類名稱privatestaticfinalString BoneCPDataSourceClassName = "com.jolbox.bonecp.BoneCPDataSource";
@Override
publicObject intercept(Invocation invocation)throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
//得到類名,方法String[] strArr = mappedStatement.getId().split("\\.");
String methodName = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
Transaction t = Cat.newTransaction("SQL", methodName);
//得到sql語句Object parameter =null;
if(invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
}
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Configuration configuration = mappedStatement.getConfiguration();
String sql = showSql(configuration, boundSql);
//獲取SQL類型SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
Cat.logEvent("SQL.Method", sqlCommandType.name().toLowerCase(), Message.SUCCESS, sql);
String s =this.getSQLDatabase();
Cat.logEvent("SQL.Database", s);
Object returnObj =null;
try {
returnObj = invocation.proceed();
t.setStatus(Transaction.SUCCESS);
} catch (Exception e) {
Cat.logError(e);
} finally {
t.complete();
}
return returnObj;
}
private DataSource getDataSource() {
org.apache.ibatis.transaction.Transaction transaction =this.target.getTransaction();
if(transaction ==null) {
logger.error(String.format("Could not find transaction on target [%s]",this.target));
returnnull;
}
if(transactioninstanceof SpringManagedTransaction) {
String fieldName = "dataSource";
Field field = ReflectionUtils.findField(transaction.getClass(), fieldName, DataSource.class);
if(field ==null) {
logger.error(String.format("Could not find field [%s] of type [%s] on target [%s]",
fieldName, DataSource.class,this.target));
return null;
}
ReflectionUtils.makeAccessible(field);
DataSource dataSource = (DataSource) ReflectionUtils.getField(field, transaction);
return dataSource;
}
logger.error(String.format("---the transaction is not SpringManagedTransaction:%s", transaction.getClass().toString()));
return null;
}
/** * 重寫 getSqlURL 方法
*
* @author fanlychie (https://github.com/fanlychie)
*/private String getSqlURL() {
// 客戶端使用的數(shù)據(jù)源DataSource dataSource =this.getDataSource();
if(dataSource !=null) {
// 處理常見的數(shù)據(jù)源switch (dataSource.getClass().getName()) {
// druidcase DruidDataSourceClassName:
returngetDataSourceSqlURL(dataSource, DruidDataSourceClassName, "getUrl");
// dbcpcase DBCPBasicDataSourceClassName:
returngetDataSourceSqlURL(dataSource, DBCPBasicDataSourceClassName, "getUrl");
// dbcp2case DBCP2BasicDataSourceClassName:
returngetDataSourceSqlURL(dataSource, DBCP2BasicDataSourceClassName, "getUrl");
// c3p0case C3P0ComboPooledDataSourceClassName:
returngetDataSourceSqlURL(dataSource, C3P0ComboPooledDataSourceClassName, "getJdbcUrl");
// HikariCPcase HikariCPDataSourceClassName:
returngetDataSourceSqlURL(dataSource, HikariCPDataSourceClassName, "getJdbcUrl");
// BoneCPcase BoneCPDataSourceClassName:
returngetDataSourceSqlURL(dataSource, BoneCPDataSourceClassName, "getJdbcUrl");
}
}
returnnull;
}
/** * 獲取數(shù)據(jù)源的SQL地址
*
* @param dataSource 數(shù)據(jù)源
* @param runtimeDataSourceClassName 運(yùn)行時(shí)真實(shí)的數(shù)據(jù)源的類名稱
* @param sqlURLMethodName 獲取SQL地址的方法名稱
*
* @author fanlychie (https://github.com/fanlychie)
*/private String getDataSourceSqlURL(DataSource dataSource, String runtimeDataSourceClassName, String sqlURLMethodName) {
Class dataSourceClass =null;
try {
dataSourceClass = Class.forName(runtimeDataSourceClassName);
} catch (ClassNotFoundException e) {}
Method sqlURLMethod = ReflectionUtils.findMethod(dataSourceClass, sqlURLMethodName);
return (String) ReflectionUtils.invokeMethod(sqlURLMethod, dataSource);
}
private String getSQLDatabase() {// String dbName = RouteDataSourceContext.getRouteKey();String dbName =null;//根據(jù)設(shè)置的多數(shù)據(jù)源修改此處,獲取dbnameif(dbName ==null) {
dbName = "DEFAULT";
}
String url = CatMybatisPlugin.sqlURLCache.get(dbName);
if(url !=null) {
return url;
}
url =this.getSqlURL();//目前監(jiān)控只支持mysql ,其余數(shù)據(jù)庫需要各自修改監(jiān)控服務(wù)端if(url ==null) {
url = String.format(EMPTY_CONNECTION, dbName);
}
CatMybatisPlugin.sqlURLCache.put(dbName, url);
return url;
}
/**
* 解析sql語句
* @param configuration
* @param boundSql
* @return
*/
public String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if(parameterMappings.size() > 0 && parameterObject !=null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} elseif (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
}
}
}
}
return sql;
}
/**
* 參數(shù)解析
* @param obj
* @return*/
private String getParameterValue(Object obj) {
String value =null;
if(objinstanceof String) {
value = "'" + obj.toString() + "'";
} elseif(objinstanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(newDate()) + "'";
} else {
if(obj !=null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}
@Override
public Object plugin(Object target) {
if(targetinstanceof Executor) {
this.target = (Executor) target;
returnPlugin.wrap(target,this);
}
return target;
}
@Override
publicvoid setProperties(Properties properties) {
}
}
2.將mybatis攔截器注入到sqlSessionFactory
在MybatisConfigurer.java中添加代碼
//添加CAT插件CatMybatisPlugin catMybatisPlugin =new CatMybatisPlugin();
factory.setPlugins(newInterceptor[]{catMybatisPlugin});
就可以看到test輸出到cat的SQL:

注意:環(huán)境規(guī)范
Windows環(huán)境(具體在哪個(gè)盤下,取決于你的項(xiàng)目): 新建D:/data/appdatas/cat/client.xml目錄和文件新建D:/data/applogs/cat/目錄Linux環(huán)境: 新建/data/appdatas/cat/client.xml新建/data/applogs/cat/目錄注意:目錄要賦予讀寫權(quán)限client.xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<config mode="client" xmlns:xsi="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="config.xsd">
<servers>
<server ip="172.30.201.159" port="2280" http-port="8080"/>
</servers>
</config>
注:
引用原鏈接:
cat搭建部署詳細(xì)步驟(美團(tuán)開源cat監(jiān)控)
