---
title: "openfire(3)数据库浅析"
author: "buerkai"
date: "2013-03-17T19:18:00Z"
tags: []
categories: ["企业架构"]
slug: "openfire-3"
draft: false
lastmod: "2013-03-17T19:02:06Z"
id: 1830823
url: "https://buerkai.iteye.com/blog/1830823"
---

openfire 中的连接有几种，可以自己实现接口ConnectionProvider，修改openfire.xml中的connectionProvider的属性为自己实现的类。

&lt;connectionProvider&gt;  
    &lt;className&gt;org.jivesoftware.database.DefaultConnectionProvider&lt;/className&gt;  
  &lt;/connectionProvider&gt;  
  &lt;database&gt;  
    &lt;defaultProvider&gt;  
      &lt;driver&gt;com.mysql.jdbc.Driver&lt;/driver&gt;  
      &lt;serverURL&gt;jdbc:mysql://localhost:3306/openfire?useUnicode=true&amp;amp;characterEncoding=UTF-8&amp;amp;zeroDateTimeBehavior=convertToNull&lt;/serverURL&gt;  
      &lt;username&gt;root&lt;/username&gt;  
      &lt;password&gt;admin&lt;/password&gt;  
      &lt;testSQL&gt;select 1&lt;/testSQL&gt;  
      &lt;testBeforeUse&gt;false&lt;/testBeforeUse&gt;  
      &lt;testAfterUse&gt;false&lt;/testAfterUse&gt;  
      &lt;minConnections&gt;5&lt;/minConnections&gt;  
      &lt;maxConnections&gt;25&lt;/maxConnections&gt;  
      &lt;connectionTimeout&gt;1.0&lt;/connectionTimeout&gt;  
    &lt;/defaultProvider&gt;  
  &lt;/database&gt;

 

openfire实现了3个相关的接口，JNDIDataSourceProvider，EmbeddedConnectionProvider，DefaultConnectionProvider（默认的连接管理器），下面将分别解析这三个类。

 

 

1\. DefaultConnectionProvider：是openfire提供的默认连接管理器，使用了org.logicalcobwebs.proxool.ProxoolDriver提供的连接池，

其中ConnectionProvider的start方法如下，主要设置连接池的相关参数

 

 public void start() {  
        proxoolURL = "proxool.openfire:"+getDriver()+":"+getServerURL();  
        settings = new Properties();  
        settings.setProperty("proxool.maximum-activetime", Integer.toString(activeTimeout));  
        settings.setProperty("proxool.maximum-connection-count", Integer.toString(getMaxConnections()));  
        settings.setProperty("proxool.minimum-connection-count", Integer.toString(getMinConnections()));  
        settings.setProperty("proxool.maximum-connection-lifetime", Integer.toString((int)(86400000 * getConnectionTimeout())));  
        settings.setProperty("proxool.test-before-use", testBeforeUse.toString());  
        settings.setProperty("proxool.test-after-use", testAfterUse.toString());  
        settings.setProperty("proxool.house-keeping-test-sql", testSQL);  
        settings.setProperty("user", getUsername());  
        settings.setProperty("password", (getPassword() != null ? getPassword() : ""));  
    }

 

2.EmbeddedConnectionProvider（嵌入式连接管理器），主要是用于openfire中采用的hsqldb.

  public Connection getConnection() throws SQLException {  
        try {  
            Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");  
            return DriverManager.getConnection(proxoolURL, settings);  
        }  
        catch (ClassNotFoundException e) {  
            throw new SQLException("EmbeddedConnectionProvider: Unable to find driver: "+e);  
        }  
    }

，此也采用org.logicalcobwebs.proxool.ProxoolDriver代理连接池。

 

hsqldb，的存放地址为openfire目录下的embedded-db中。

  File databaseDir = new File(JiveGlobals.getHomeDirectory(), File.separator + "embedded-db");  
        // If the database doesn't exist, create it.  
        if (!databaseDir.exists()) {  
            databaseDir.mkdirs();  
        }

        try {  
            serverURL = "jdbc:hsqldb:" + databaseDir.getCanonicalPath() + File.separator + "openfire";  
        }  
        catch (IOException ioe) {  
            Log.error("EmbeddedConnectionProvider: Error starting connection pool: ", ioe);  
        }

 

Hsqldb是一个开放源代码的JAVA数据库，其具有标准的SQL语法和JAVA接口，它可以自由使用和分发，非常简洁和快速的。具有Server模式，进程内模式(In-Process)和内存模式(Memory-Only)三种。运行Hsqldb需要hsqldb.jar包, 它包含了一些组件和程序。每个程序需要不同的命令来运行。

更多关于Hsqldb请查看其它相关资料，在openfire中使用的标准的sql。

 

 

3.JNDIDataSourceProvider

openfire提供的JNDI连接器。

 public void start() {  
        if (dataSourceName == null || dataSourceName.equals("")) {  
            Log.error("No name specified for DataSource. JNDI lookup will fail", new Throwable());  
            return;  
        }  
        try {  
            Properties contextProperties = new Properties();  
            for (String key: jndiPropertyKeys) {  
                String value = JiveGlobals.getXMLProperty(key);  
                if (value != null) {  
                    contextProperties.setProperty(key, value);  
                }  
            }  
            Context context;  
            if (contextProperties.size() &gt; 0) {  
                context = new InitialContext(contextProperties);  
            }  
            else {  
                context = new InitialContext();  
            }  
            dataSource = (DataSource)context.lookup(dataSourceName);  
        }  
        catch (Exception e) {  
            Log.error("Could not lookup DataSource at '" + dataSourceName + "'", e);  
        }  
    }

 

其主要属性有：

 private static final String\[] jndiPropertyKeys = {  
        Context.APPLET,  
        Context.AUTHORITATIVE,  
        Context.BATCHSIZE,  
        Context.DNS\_URL,  
        Context.INITIAL\_CONTEXT\_FACTORY,  
        Context.LANGUAGE,  
        Context.OBJECT\_FACTORIES,  
        Context.PROVIDER\_URL,  
        Context.REFERRAL,  
        Context.SECURITY\_AUTHENTICATION,  
        Context.SECURITY\_CREDENTIALS,  
        Context.SECURITY\_PRINCIPAL,  
        Context.SECURITY\_PROTOCOL,  
        Context.STATE\_FACTORIES,  
        Context.URL\_PKG\_PREFIXES  
    };

具体可查看JNDI相关。

 

4.实现自己的连机器（ConnectionProvider），

public interface ConnectionProvider {

    public boolean isPooled();

     
    public Connection getConnection() throws SQLException;

     
    public void start();

     
    public void restart();  
    public void destroy();  
}

需要写以上相关方法，可以用通用的连接池，c3p0,阿帕奇的dbcp等。

 

对于openfire比较遗憾的是，没有相关事务的管理，关于sql的处理在各个模块都有，耦合性较大。

 

此篇文章就到此，稍后会有更多关于openfire的个人解读。

联系方式（qq）:851392159

出处：[http://buerkai.iteye.com](/)