SonarQube是管理代碼質量一個開放平臺,可以快速的定位代碼中潛在的或者明顯的錯誤,下面將會介紹一下這個工具的安裝、配置以及使用。
準備工作;
1、jdk(不再介紹)
2、sonarqube:http://www.sonarqube.org/downloads/
3、SonarQube+Scanner:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
4、mysql數據庫(不再介紹)
SonarQube安裝
預置條件
1.已安裝JAVA環境
2.已安裝有MySQL數據庫
1.下載好sonarqube後,解壓打開bin目錄,啓動相應OS目錄下的StartSonar。如本文演示使用的是win的64位系統,則打開F:\sonar\sonarqube-7.1\bin\windows-x86-64\StartSonar.bat
2.啓動瀏覽器,訪問http://localhost:9000,如出現下圖則表示安裝成功。
數據庫配置
1.打開mysql,新建一個數據庫。
2.打開sonarqube安裝目錄下的F:\sonar\sonarqube-7.1\conf\sonar.properties文件
3.在mysql5.X節點下輸入以下信息
sonar.jdbc.url=jdbc:mysql://127.0.0.1:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
sonar.jdbc.username=root
sonar.jdbc.password=root
sonar.sorceEncoding=UTF-8
sonar.login=admin
sonar.password=admin
4.重啓sonarqube服務,再次訪問http://localhost:9000,會稍微有點慢,因爲要初始化數據庫信息
5.數據庫初始化成功後,登錄
6.搜索chinese Pack,安裝中文語言包
7.安裝成功後,重啓sonarqube服務,再次訪問http://localhost:9000/,即可看到中文界面
配置sonar scanner
二.安裝
第一步:
將下載的壓縮包解壓縮到任意目錄;
第二步:
打開Sonar Scanner根目錄下的/conf/sonar-scanner.properties文件,配置如下:
sonar.host.url=http://localhost:9000 //sonar.host.url配置的是SonarQube服務器的地址
第三步:
新建系統變量:
SONAR_SCANNER_HOME=Sonar Scanner根目錄
修改系統變量path,新增%SONAR_SCANNER_HOME%\bin(不新建SONAR_SCANNER_HOME直接新增path亦可);
打開cmd面板,輸入sonar-scanner -version,出現下圖,則表示環境變量設置成功:
三.使用
在項目根目錄下新建sonar-project.properties文件,內容如下
# must be unique in a given SonarQube instance
sonar.projectKey=esb
# this is the name displayed in the SonarQube UI
sonar.projectName=esb
sonar.projectVersion=1.0
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Since SonarQube 4.2, this property is optional if sonar.modules is set.
# If not set, SonarQube starts looking for source code from the directory containing
# the sonar-project.properties file.
sonar.sources=F:/program/esb/src
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
sonar.my.property=value
sonar.java.binaries=F:/program/esb/WebRoot/WEB-INF/classes
設置完後,打開cmd面板,進入項目根目錄下,然後輸入“sonar-scanner”命令,執行代碼分析:
分析成功的界面爲:
然後打開http://localhost:9000 (SonarQube服務器),輸入賬號密碼,即可查看代碼分析結果。