前言
Sonarqube為靜态代碼檢查工具,采用B/S架構,幫助檢查代碼缺陷,改善代碼品質,提高開發速度,通過插件形式,可以支援Java、C、C++、JavaScripe等等二十幾種程式設計語言的代碼品質管理與檢測。本文介紹如何快速安裝、配置、使用Sonarqube及Sonarqube Scanner。
工作原理
Sonaqube-scanner:負責搜集代碼相關資料 (可以了解為搜集端)
Sonarqube:負責對搜集的資料進行分析,通過不同的插件算法來對這些結果進行再加工,最終以量化的方式來衡量代碼品質,最終展現給使用者。

IP | 功能 | 軟體 | 安裝路徑 | 作業系統 |
192.168.9.11 | sonarqube服務端 | jdk1.8.0_151,mysql5.7.21 sonarqube6.7 | /usr/local/ | centos7.5 |
192.168.9.12 | sonarqube-scanner用戶端 | sonarqube-scanner3.2.0 | d:/sonar | windows7 |
搭建步驟:(sever端安裝jdk mysql過程略)
sonarqube的安裝
wget https://sonarsource.bintray.com/Distribution/sonarqube/sonarqube-6.7.ziunzip sonarqube-6.7.zip -d /usr/local/useradd sonar
chown -R sonar. /usr/local/sonarqube-6.7/
sonarqube配置檔案修改
vim /usr/local/sonarqube-6.7/conf/sonar.properties
sonar.web.host=0.0.0.0
sonar.web.port=9000
sonar.jdbc.url=jdbc:mysql:sonar.jdbc.driver==sonar=password
建立資料庫 (在資料庫中建立需使用的庫)
mysql -u root -p
> CREATE USER %password> GRANT all privileges ON sonarqube.* TO sonar’@‘%password>> create database sonarqube;
啟動及關閉
cd /usr/local/sonarqube-/bin/linux-x86-64
.//sonar.sh stop
通過浏覽器登入檢視,并使用預設密碼登入。(可以在“配置”項的“應用市場”中選擇安裝中文插件來支援中文,)
sonarqube-scanner的安裝
1.下載下傳sonar-scanner-3.2.0.1227-windows.zip并解壓,将bin檔案加入環境變量path中如我的路徑D:\sonar\sonar-scanner\bin将此路徑加入path中
2.編輯配置檔案conf/sonar-scanner.properties。根據資料庫使用情況進行取消相關的注釋即可,同時需要添加資料庫使用者名和密碼資訊,即配置要通路的sonar服務和mysql伺服器位址
#Configure here general information about the environment, such as SonarQube server connection details for example
#No information about specific project should appear here
#----- Default SonarQube server
sonar.host.url=http://192.168.9.11:9000#----- Default source code encoding
#sonar.sourceEncoding=UTF-8sonar.jdbc.username=sonar
sonar.jdbc.password=passwordsonar.jdbc.url=jdbc:mysql://192.168.9.150:3306/sonarqube?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
3.編輯sonar-project.properties 放入需要掃描的project中(注意:同時要在sonarqube裡添加對應的項目名稱)
# must be unique in a given SonarQube instance
sonar.projectKey=saas_core
# this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
sonar.projectName=saas_core
sonar.projectVersion=1.0
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.# This property is optional if sonar.modules is set.
sonar.sources=saas_core
sonar.binaries=bin
sonar.language=java
sonar.java.binaries=D:\sonar\saas_core
# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8
4.sonar-scanner執行掃描分析
sonar-scanner -X
以上分析執行後,會将分析資料上傳至sonarqube,在sonarqube中分析完成後,就可以看到分析結果