SonarQube是用来检查分析静态代码质量的工具,码云用户可以使用码云提供的SonarQube服务来分析代码质量。普通用户或企业可以在本地安装一个。
对于安装过Tomcat/Nginx的java开发说,安装一个SonarQube是很简单的。
java开发中使用到的服务器的安装套路大都是
- 下载 tar.gz或zip
- 解压
- bin/start.sh或bin/start.bat
SonarQube也不例外,只是多了几步配置。本示例使用Windows7(64位)来操作的。
版本选择
我用的版本是4.5.7。最开始时使用了5.6.6版本,打开页面http://localhost:9000, 但自动跳转到了http://localhost:9000/maintain页面, 查看日志,报了如下错误:
ActiveRecord :: JDBCError : Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging. InnoDB is limited to row-logging when transaction isolation level is READ COMMITTED or READ UNCOMMITTED.: INSERT INTO schema_migrations (version) VALUES ('710')
然后网上查资料后,在mysql的my.ini中添加如下设置
binlog_format=row
之间报了如下错误:
high disk watermark [90%] exceeded on [xPjWeyYxRVKex_7MUP7qVw][sonar-1495881147356] free: 22.4mb[0%], shards will be relocated away from this node
可能是因为磁盘没空间了,但我电脑磁盘空间大着呢。
无奈改用6.3.1,报的错误更是奇葩,服务启动不了,查询logs/sonar.log日志,发现
Process[es] is stopping
Process[web] failed to start Process[es] is stopped
继而查看logs/web.log日志,发现
MessageException: Current version is too old. Please upgrade to Long Term Support version firstly
又是查找资料,看了两个stackoverflow页面, https://stackoverflow.com/questions/38744817/sonarqube-current-version-is-too-old-please-upgrade-to-long-term-support-ver?noredirect=1&lq=1和 https://stackoverflow.com/questions/34947417/messageexception-current-version-is-too-old-please-upgrade-to-long-term-suppor
最后索性改用低版本的4.5.7,启动后竟然能访问到http://localhost:9000页面。
配置及安装
- 新建数据库sonar,字符集为UTF-8。
- 在maven的settings.xml中添加
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.jdbc.url>jdbc : mysql : //localhost:3306/sonar?useUnicode=true&characterEncoding=utf8</sonar.jdbc.url>
<sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
<sonar.jdbc.username>root</sonar.jdbc.username>
<sonar.jdbc.password>root</sonar.jdbc.password>
<sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>
</profile>
注意:请自行去掉sonar.jdbc.url中的空格(不然显示的就不正常)
- 修改conf/sonar.properties文件的三处:
sonar.jdbc.username=root sonar.jdbc.password=root sonar.jdbc.url=jdbc : mysql : //localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
和第二步的配置一样。
-
启动SonarQube,bin/目录下有对应操作系统的启脚本,我的Windows7就执行bin\windows-x86-64目录下的StartSonar.bat。
-
在项目中执行
mvn clean sonar:sonar
。说明:在我第一次安装这个时(2017年10月25日),执行mvn clean sonar:sonar就能成功,但今天(2018年04月09日)再次执行时却有一个错误提醒:
With SonarQube server prior to 5.6, it is recommended to use the sonar-maven-plugin 3.3
上网查找了一下,在maven项目的父pom.xml中添加
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
即可执行成功。
使用
执行命令后访问http://localhost:9000即可在页面右上角看到PROJECTS列表,点击项目即可看到质量分析。