以前关注点一直在怎么提高应用程序的质量,没太在意代码级别的质量。最近因为某些因素的推动,需要关注到代码级别的质量去,把质量工作尽量往前推,也符合质量控制的原则。
试用了一下sonarqube(老版本的叫sonar,ww.sonarqube.org),对代码的提升的确有很多的作用,sonarqube能从7个维度来对代码质量进行度量。多大的作用,大家实践下就很容易看出来。尤其是建议大家把rules里面的说明和例子都好好看看,对以后自己写代码的时候,质量提高有很大好处。
Sonarqube安装:
Sonarqube一共分3 部分:
以下安装步骤是Linux下的安装示例
数据库:
这里我用的是mysql数据库,直接执行SQL:
CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci; 赋予后面连接sonarqube的数据库用户读写权限即可
web服务:
修改sonarqube/conf/sonar.properties # Permissions to create tables, indices and triggers must be granted to JDBC user.# The schema must be created first.sonar.jdbc.username=mysql_usernamesonar.jdbc.password=mysql_password# Comment the following line to deactivate the default embedded database.#sonar.jdbc.url=jdbc:h2:tcp://localhost:9092/sonar#----- MySQL 5.x# Comment the embedded database and uncomment the following line to use MySQLsonar.jdbc.url=jdbc:mysql://192.168.22.99:3306/sonarqube?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=tsonar.web.host=0.0.0.0sonar.web.context=/sonarqubesonar.web.port=9001 sonarqube自带web服务器,性能也足够好,不需要配置tomcat什么的,到这里整个sonar web服务配置完成了,到sonarqube/bin/linux-x86-64目录下,启动./sonar.sh start即可,启动后有任何问题可以查看log: sonarqube/logs/sonar.log, 通过浏览器访问http://192.168.22.99:9001/sonarqube, 打开登陆页面,默认管理员账户是admin/admin
分析器:
Sonarqube通过插件 支持20+种语言, Java, python, C#, C/C++, PL/SQL, Cobol等, 但C语言的插件是收费的。到这里http://docs.codehaus.org/display/SONAR/Plugin+Library 下载对应语言的插件,放置到sonarqube/extensions/plugins目录下,重启web服务即可。
分析器主要5种:
SonarQube Runner(万能,支持后面几种方式的工程),
Maven(和maven编译工程集成),
SonarQube Ant Task(和ant编译工程集成),
Gradle(和Gradle编译工具集成,很少听过),
CI Engine(主要和Jenkins , Hudson等CI工具集成)。
以下主要讲Sonarqube runner分析器的使用:
下载Sonarqube 分析器:http://docs.codehaus.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner, 解压后修改conf目录下的sonar-runner.properties, 如下例子。 #----- Default SonarQube serversonar.host.url=http://192.168.23.94:9001/sonarqube#----- PostgreSQL#sonar.jdbc.url=jdbc:postgresql://localhost/sonar#----- MySQLsonar.jdbc.url=jdbc:mysql://192.168.23.99:3306/sonarqube_qa?useUnicode=true&characterEncoding=utf8#----- Oracle#sonar.jdbc.url=jdbc:oracle:thin:@localhost/XE#----- Microsoft SQLServer#sonar.jdbc.url=jdbc:jtds:sqlserver://localhost/sonar;SelectMethod=Cursor#----- Global database settingssonar.jdbc.username=mysql_usernamesonar.jdbc.password=mysql_password#----- Default source code encodingsonar.sourceEncoding=UTF-8#----- Security (when 'sonar.forceAuthentication' is set to 'true')sonar.login=adminsonar.password=admin 把sonarruner/bin加入到path目录下,在环境变量里面加上SONAR_RUNNER_HOME="/home//sonarruner"。 到这里整个Sonarqube的运行环境就全部配置完成了,下一篇讲解怎么运行分析器。