一、sonarQube简介
SonarQube 是一款用于代码质量管理的开源工具,它主要用于管理源代码的质量。 通过插件形式,可以支持众多计算机语言,比如 java, C#, go,C/C++, PL/SQL, Cobol, JavaScrip, Groovy 等。sonar可以通过PMD,CheckStyle,Findbugs等等代码规则检测工具来检测你的代码,帮助你发现代码的漏洞,Bug,异味等信息。
Sonar 不仅提供了对 IDE 的支持,可以在 Eclipse和 IntelliJ IDEA 这些工具里联机查看结果;同时 Sonar 还对大量的持续集成工具提供了接口支持,可以很方便地在持续集成中使用 Sonar。
二、sonarQube配置与安装
1. 下载地址
- sonarQube最新版下载地址:(最新版不支持mysql)https://www.sonarqube.org/downloads/
- 7.1版本下载地址:https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-7.1.zip
- Sonar-Scanner 2.5下载地址:https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/
2. 环境准备
(1)Java环境(1.8+)
(2)MySql数据库(5.6+)
(3)SonarQube 7.1
注意:sonarQube 7.9的版本之后就不在支持mysql,所以下载的是7.1版本。
下载完解压后如下:
3. 安装
(1)下载好sonarqube后,解压打开bin目录,启动相应OS目录下的StartSonar。我使用的是windows的64位系统,则打开bin\windows-x86-64\StartSonar.bat
。
(2)使用浏览器访问http://localhost:9000,如出现下图则表示安装成功。
4. 配置
(1)在解压目录中打开conf\sonar.properties
配置文件
(2)配置数据库:输入自己数据库的相关信息
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
sonar.jdbc.username=root
sonar.jdbc.password=123456
sonar.sorceEncoding=UTF-8
sonar.login=admin
sonar.password=admin
5.安装中文语言包
按照步骤搜索chinese Pack,安装中文语言包,安装好后重启sonor,并登录。
三、使用
- 下载sonar-scanner-2.5并解压,打开sonar-scanner-2.5\conf\sonar-runner.properties文件进行配置:输入数据库相关信息
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
sonar.jdbc.username=root
sonar.jdbc.password=123456
sonar.sorceEncoding=UTF-8
sonar.login=admin
sonar.password=admin
- 配置环境变量
a.新建变量,name=SONAR_RUNNER_HOME。value=D:\sonar\sonar-scanner-2.5
b.打开path,输入%SONAR_RUNNER_HOME%\bin;
c.sonar-runner -version,出现以下信息,则表示环境变量设置成功
- 打开要进行代码分析的项目根目录,新建sonar-project.properties文件
- 输入以下内容:
其中:projectName是项目名字,sources是源文件所在的目录
# must be unique in a given SonarQube instance
sonar.projectKey=my:project
# this is the name displayed in the SonarQube UI
sonar.projectName=apiautocore
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=src
# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8
- 设置成功后,启动sonarqube服务,并启动cmd
- 在cmd进入项目所在的根目录,输入命令:sonar-runner,分析成功后会出现下图:
- 打开http://localhost:9000/,我们会看到主页出现了分析项目的概要图:
- 点击项目,选择问题链接,会看到分析代码的bug