Sonar入門(一):簡介

什麼是Sonar?

Sonar是一個開源的代碼質量管理平臺。它能對代碼進行如下7個維度的管理。

使用插件,它可以對20多種語言進行代碼質量管理,這其中包括Java,C#,C/C++,PL/SQL等等。

安裝Sonar

1.下載sonar,地址http://www.sonarqube.org/downloads/。通常選取穩定版本下載即可,這是一個zip文件。
2.解壓下載的sonar到一個目錄。我們稱這個解壓後的路徑爲SONAR_HOME
3.進入$SONAR_HOME/bin/${os-version}/,找到sonar.sh,執行./sonar.sh console即可。在windows下是StartSonar.bat。
4.現在進入http://localhost:9000,就看到了界面。默認的登錄使用admin:admin

這個時候,Sonar已經運行啦。但是在生產環境是不行的。上面跑起來的只是一個樣例,使用的是h2內存數據庫。我們可不想重啓服務後,生產環境的數據都沒了。

配置Sonar數據庫

1.首先新建一個數據庫。

CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;  
grant all privileges on sonar.* to 'sonar'@'%' identified by '你的密碼';  
flush privileges;

這樣就準備好了數據庫sonar,並授權給sonar這個用戶。

2.找到$SONAR_HOME/conf/sonar.properties。註釋掉默認的數據庫配置,然後配上自己的數據庫信息即可。這裏以mysql爲例。

# Comment the following line to deactivate the default embedded database.
#sonar.jdbc.url:                            jdbc:h2:tcp://localhost:9092/sonar
#sonar.jdbc.driverClassName:                org.h2.Driver

-------------------
# The schema must be created first.

sonar.jdbc.username: sonarsonar.jdbc.password: sonar #----- MySQL 5.x # Comment the embedded database and uncomment the following line to use MySQL sonar.jdbc.url: jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true

# Optional properties
sonar.jdbc.driverClassName:                com.mysql.jdbc.Driver

配置好之後,這樣所有的數據都會存放到mysql內啦。不用再擔心數據問題啦。要添加其他數據庫,同理。

把Sonar變爲中文

英文看這不方便啊。有2種方法可以將Sonar變爲中文界面。

1.用管理員登錄後,在Update Center種找到Localization裏的Chinese Pack安裝就可以了。
2.直接下載http://repository.codehaus.org/org/codehaus/sonar-plugins/l10n/sonar-l10n-zh-plugin/1.6/sonar-l10n-zh-plugin-1.6.jar這個插件jar包到$SONAR_HOME/extensions/plugins內,重啓即可。

把Sonar放到JEE容器內

默認的情況下,sonar啓動是採用內置的jetty的,爲了方便管理,一般在生產環境可以放到JEE容器內,這裏就以Tomcat爲例了。
Sonar在經過上面幾步的配置後,已經滿足了基本的需求。接下來就可以進入到$SONAR_HOME/war/內。執行build-war命令。這樣就生成了一個sonar.war,把這個war包發佈到Tomcat即可。

如何對源碼進行檢測

1.配置maven的settings.xml,添加一下內容:

    <profile>
         <id>sonar</id>
         <activation>
             <activeByDefault>true</activeByDefault>
         </activation>
         <properties>
              <sonar.jdbc.url>
              jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8
              </sonar.jdbc.url>
              <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
              <sonar.jdbc.username>sonar</sonar.jdbc.username>
              <sonar.jdbc.password>sonar</sonar.jdbc.password>
             <sonar.host.url>http://localhost:9000/sonar</sonar.host.url>
         </properties>
      </profile>

其中的數據庫配置以及sonar主機地址都依據實際進行修改即可。
2.在maven項目種執行

mvn clean install
mvn sonar:sonar

3.打開sonar主頁,就可以看到結果了。

Sonar與Jenkins的集成。

1.安裝jenkins-sonar-plugin到Jenkins內。
2.在Jenkins裏的系統配置中,填寫Sonar安裝信息。
3.在Jenkins的JOB中,配置post-build action中添加上Sonar即可。這樣在項目構建後,會自動的執行Sonar分析。並將結果放在首頁進行展現。

-- Main.shenyanchao - 2013-09-04
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章