前言:
SonarQube是一個開源的代碼質量管理平臺,能很好的幫我們檢測代碼質量,也經常被結合使用在持續(xù)交付的流程中,所以今天我們就來了解一下。
一,SonarQube的安裝
1,訪問SonarQube的官網,點擊下載好sonarqube.zip文件后,解壓至本地,本文演示使用的是win10的64位系統(tǒng),所以點擊D:\sonarqube-7.5\sonarqube-7.5\bin\windows-x86-64\StartSonar.bat啟動sonarqube。(此處根據自己所處的系統(tǒng)選擇不同文件夾下的啟動文件啟動)

啟動成功后如下圖:

2,打開瀏覽器訪問http://localhost:9000,如出現sonarqube頁面則表示安裝成功;
二,SonarQube的配置
1,打開數據庫,新建一個sonar數據庫
2,打開sonarqube安裝目錄下的D:\sonarqube-7.5\sonarqube-7.5\conf\sonar.properties文件,編輯文件
3,在MySQL >=5.6 && <8.0后面加入數據庫配置;
#----- MySQL >=5.6 && <8.0
# Support of MySQL is dropped in Data Center Editions and deprecated in all other editions
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
#sonar.jdbc.url=jdbc:mysql://數據庫ip:3306/db_sonar?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false
#sonar.jdbc.username=數據庫用戶名
#sonar.jdbc.password=數據庫密碼
#sonar.sorceEncoding=UTF-8
#sonar.scm.disabled=true
配置好數據庫信息后,重啟SonarQube,再次訪問http://localhost:9000,SonarQube到這里基礎數據庫配置就配置成功啦
三,SonarQube的掃描
從官網可以看到,SonarQube支持以下方式來進行項目的掃描;
1,直接使用SonarQube scanner即掃描儀來進行分析
2,使用SonarQube掃描儀分析Maven
3,使用SonarQube掃描儀分析Gradle
4,使用SonarQube掃描儀分析ant
5,使用SonarQube掃描儀分析Jenkins
6,使用SonarQube掃描儀分析MSBuild(比較少見)
7,使用SonarQube掃描儀分析VSTS-TFS(比較少見)
掃描方式具體選擇,請根據實際掃描項目所使用的構建工具進行選擇:常見的有maven,ant,gradle;如果本地未搭建開發(fā)環(huán)境,此時使用SonarQube scanner就很方便了;SonarQube同時也提供了對jenkins的插件支持;因為樓主要掃描的項目是使用maven來管理項目的,下面介紹maven項目的掃描過程:
(1)maven項目的掃描配置
1, 找到位置 $MAVEN_HOME/conf 或者是 ~/.m2 下的settings.xml
2,添加如下配置:
<settings>
<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Optional URL to server. Default value is http://localhost:9000 -->
<sonar.host.url>
http://loaclhost:9000
</sonar.host.url>
</properties>
</profile>
</profiles>
</settings>
<sonar.host.url>是指sonar 服務器地址
**注意:直接加進去會報語法錯誤,因為標簽沖突了,將<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>添加到文件原有的<pluginGroups></pluginGroups>中,將上文配置中的<profile> 到</profile>的內容添加到文件原有的<profiles></profiles>中,就不會報錯了
3,運行編輯器的命令窗口,執(zhí)行mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar
遇到報錯:SCM provider autodetection failed. Both svn and git claim to support this project. Please use sonar.scm.provider to define SCM of your project.
在命令中添加參數 -Dsonar.scm.provider=git就好啦~
mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar -Dsonar.scm.provider=git
4,執(zhí)行成功的話,訪問http://localhost:9000 ,就能查看項目掃描結果啦~ 如下圖:

根據掃描結果優(yōu)化代碼后,只要再執(zhí)行命令就能更新掃描結果啦~ 如果需要使用別的技術棧掃描的話,請參考上面官方文檔鏈接去嘗試把~ fighting~
以上~對你有幫助的話,點個喜歡??吧~~