SonarQube是管理代码质量的开放平台,可以快速的定位代码中潜在的或者明显的错误

准备工作

下载sonar:https://www.sonarqube.org/downloads/,我使用的是7.0版本

安装mysql

需要事先装好mysql,需要5.6以上版本,我这边安装的是5.7.30

创建sonar用户

CREATE USER 'sonar'@'%' IDENTIFIED BY 'sonar';
CREATE DATABASE sonar CHARACTER SET UTF8;
GRANT ALL PRIVILEGES ON sonar.* TO 'sonar'@'%';

创建sonar系统用户

useradd sonar
passwd sonar

安装sonar

#解压
unzip sonarqube-7.0.zip

#修改配置文件conf/sonar.properties
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:mysql://192.168.37.137:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
sonar.web.host=0.0.0.0
sonar.web.context=

启动sonar

#改变权限
chown -R sonar:sonar /usr/local/sonarqube-7.0
su sonar
/usr/local/sonarqube-7.0/bin/linux-x86-64/sonar.sh start

最后通过ip:9000访问,默认用户名admin,密码admin

安装中文插件

下载sonar-l10n-zh-plugin-1.16.jar插件 https://github.com/SonarQubeCommunity/sonar-l10n-zh/releases/tag/sonar-l10n-zh-plugin-1.16
将插件放到/usr/local/sonarqube-7.0/extensions/plugins目录下

/usr/local/sonarqube-7.0/bin/linux-x86-64/sonar.sh restart

安装SonarScanner

下载 https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/

unzip sonar-scanner-cli-4.4.0.2170-linux.zip
#/etc/profile 配置环境变量
export SONAR_SCANNER_HOME=/usr/local/sonar-scanner-4.4.0.2170-linux
PATH=${SONAR_SCANNER_HOME}/bin
export PATH
#使生效
source /etc/profile
#查看版本
sonar-scanner -v

配置sonar-scanner,关联sonarqube

在/usr/local/sonar-scanner-4.4.0.2170-linux/conf/sonar-scanner.properties中添加如下内容

sonar.host.url=http://127.0.0.1:9000
sonar.login=admin
sonar.password=admin
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:mysql://192.168.37.137:3306/sonar?useUnicode=true&characterEncoding=utf8

扫描代码

在此之前需要安装需要的插件,例如sonar-java-plugin、sonar-findbugs-plugin、sonar-pdfreport-plugin-3.0.2等
在需要扫描的项目根目录下创建sonar-project.properties

# must be unique in a given SonarQube instance
sonar.projectKey=myproject
# this is the name displayed in the SonarQube UI
sonar.projectName=myproject
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=.
sonar.java.binaries=target/classes

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8

#pdf
#sonar.pdf.username=admin
#sonar.pdf.password=admin
#sonar.pdf.skip=false

执行sonar-scanner,完成后在sonarqube的web界面查看