使用JDBC DataSourcePool的SQL連線

與SQL資料庫(以及其他非HTTP/HTTPS服務)的連線必須從AEM使用代理連線,包括使用AEM的DataSourcePool OSGi服務來管理連線的連線。

進階網路支援

下列進階網路選項支援下列程式碼範例。

在執行本教學課程之前,請確定已設定適當的進階網路設定。

OSGi設定

OSGi設定的連線字串使用:

  • 透過OSGi設定環境變數 $[env:AEM_PROXY_HOST;default=proxy.tunnel]AEM_PROXY_HOST值作為連線的主機
  • 30001是Cloud Manager連線埠轉寄對應30001mysql.example.com:3306portOrig

由於密碼不得儲存在程式碼中,因此最好透過OSGi設定變數、使用AIO CLI或Cloud Manager API來設定SQL連線的使用者名稱和密碼。

  • ui.config/src/jcr_root/apps/wknd-examples/osgiconfig/config/com.day.commons.datasource.jdbcpool.JdbcPoolService~wknd-examples-mysql.cfg.json
{
  "datasource.name": "wknd-examples-mysql",
  "jdbc.driver.class": "com.mysql.jdbc.Driver",
  "jdbc.connection.uri": "jdbc:mysql://$[env:AEM_PROXY_HOST;default=proxy.tunnel]:30001/wknd-examples",
  "jdbc.username": "$[env:MYSQL_USERNAME;default=mysql-user]",
  "jdbc.password": "$[secret:MYSQL_PASSWORD]"
}

以下aio CLI命令可用於根據每個環境設定OSGi秘密:

$ aio cloudmanager:set-environment-variables --programId=<PROGRAM_ID> <ENVIRONMENT_ID> --secret MYSQL_USERNAME "mysql-user" --secret MYSQL_PASSWORD "password123"

程式碼範例

此Java™程式碼範例屬於透過AEM DataSourcePool OSGi服務連線至外部MySQL資料庫的OSGi服務。
DataSourcePool OSGi Factory設定接著會指定透過enableEnvironmentAdvancedNetworkingConfiguration作業中的portForwards規則對應到外部主機和連線埠mysql.example.com:3306的連線埠(30001)。

...
"portForwards": [{
    "name": "mysql.example.com",
    "portDest": 3306,
    "portOrig": 30001
}]
...
  • core/src/com/adobe/aem/wknd/examples/connections/impl/JdbcExternalServiceImpl.java
package com.adobe.aem.wknd.examples.core.connections.impl;

import com.adobe.aem.wknd.examples.core.connections.ExternalService;
import com.day.commons.datasource.poolservice.DataSourceNotFoundException;
import com.day.commons.datasource.poolservice.DataSourcePool;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class JdbcExternalServiceImpl implements ExternalService {
    private static final Logger log = LoggerFactory.getLogger(JdbcExternalServiceImpl.class);

    @Reference
    private DataSourcePool dataSourcePool;

    // The datasource.name value of the OSGi configuration containing the connection this OSGi component will use.
    private static final String DATA_SOURCE_NAME = "wknd-examples-mysql";

    @Override
    public boolean isAccessible() {

        try {
            // Get the JDBC data source based on the named OSGi configuration
            DataSource dataSource = (DataSource) dataSourcePool.getDataSource(DATA_SOURCE_NAME);

            // Establish a connection with the external JDBC service
            // Per the OSGi configuration, this will use the injected $[env:AEM_PROXY_HOST] value as the host
            // and the port (30001) mapped via Cloud Manager API call
            try (Connection connection = dataSource.getConnection()) {

                // Validate the connection
                connection.isValid(1000);

                // Close the connection, since this is just a simple connectivity check
                connection.close();

                // Return true if AEM could reach the external JDBC service
                return true;
            } catch (SQLException e) {
                log.error("Unable to validate SQL connection for [ {} ]", DATA_SOURCE_NAME, e);
            }
        } catch (DataSourceNotFoundException e) {
            log.error("Unable to establish an connection with the JDBC data source [ {} ]", DATA_SOURCE_NAME, e);
        }

        return false;
    }
}

MySQL驅動程式相依性

AEM as a Cloud Service通常需要您提供Java™資料庫驅動程式來支援連線。 提供驅動程式通常最好透過all套件將包含這些驅動程式的OSGi套件成品內嵌至AEM專案中。

Reactor pom.xml

將資料庫驅動程式相依性包含在Reactor pom.xml中,然後在all子專案中參照它們。

  • pom.xml
...
<dependencies>
    ...
    <!-- MySQL Driver dependencies -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>[8.0.27,)</version>
        <scope>provided</scope>
    </dependency>
    ...
</dependencies>
...

所有pom.xml

將資料庫驅動程式相依性成品內嵌到all套件中,以部署這些成品,並可在AEM as a Cloud Service上使用。 這些成品​ 必須 ​是匯出資料庫驅動程式Java™類別的OSGi組合。

  • all/pom.xml
...
<embededs>
    ...
    <!-- Include the MySQL Driver OSGi bundles for deployment to the project -->
    <embedded>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <target>/apps/wknd-examples-vendor-packages/application/install</target>
    </embedded>
    ...
</embededs>

...

<dependencies>
    ...
    <!-- Add MySQL OSGi bundle artifacts so the <embeddeds> can add them to the project -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>provided</scope>
    </dependency>
    ...
</dependencies>
...
recommendation-more-help
4859a77c-7971-4ac9-8f5c-4260823c6f69