-
Notifications
You must be signed in to change notification settings - Fork 9
cleardb
ClearDB はクラウド MySQL アプリケーションのための、強力で強固な database-as-a-service です。
次の指示に従えば、ClearDB をすぐにインストールして使えます!次のコマンドを実行して、アプリケーションに ClearDB を追加してください。
:::term
$ heroku addons:add cleardb:ignite
-----> Adding cleardb to sharp-mountain-4005... done, v18 (free)
次のコマンドでデータベース URL を取得できます。
:::term
$ heroku config | grep CLEARDB_DATABASE_URL
CLEARDB_DATABASE_URL => mysql://adffdadf2341:adf4234@us-cdbr-east.cleardb.com/heroku_db?reconnect=true
CLEARDB_DATABASE_URL の設定値をコピーしてください。
**Note**: もしも Ruby on Rails で `mysql2` の gem を使うのであれば、CLEARDB_DATABASE_URL にある `mysql://` スキーマを `mysql2://` に変更してください。
:::term
$ heroku config:add DATABASE_URL='mysql://adffdadf2341:adf4234@us-cdbr-east.cleardb.com/heroku_db?reconnect=true'
Adding config vars:
DATABASE_URL => mysql2://adffd...b?reconnect=true
Restarting app... done, v61.
これだけです!
このチュートリアルは、あなたもしくはあなたのチームの誰かが MySQL の知識および Heroku クラウド上で選択した言語もしくはフレームワークで MySQL を設定し、利用する知識を十分に持っていると仮定しています。 また、アドオンの準備やアプリケーションで MySQL を利用するための環境変数の使い方など Heroku コマンドラインの基本的な機能に通じていることも仮定しています。
開発中、ローカルの MySQL インスタンスでアプリケーションを動かしていることと思います。 ClearDB はネイティブの MySQL を使ってアプリケーションを動かすので、ClearDB で動かすとき、特別なデータハンドリングや変換を気にする必要はありません。 ClearDB Heroku アドオンを使うと、ClearDB はあなたの Heroku アプリケーションスタックの一部になります。 ここでの目標は、ローカル環境での作業から Heroku/ClearDB 環境での作業へとシームレスな移行を確実にすることです。
The ClearDB Heroku Add-On provisions your database on two "multi-master" database servers in two different Amazon EC2 regions to ensure absolute data availability. However, when you provision your ClearDB add-on, you will only receive a single database URL, which connects to our high availability router network.
The primary master node is located right next to Heroku, in Amazon's EC2 "US-East" region. The secondary master node is located in Amazon's EC2 "US-West" region, so even if there are network problems, EBS failures, even natural disasters, your data will still be online and available.
Upon provisioning the ClearDB Heroku Add-On in your Heroku environment, you will receive a database URL labeled CLEARDB_DATABASE_URL
. This URL is your link to the ClearDB Cluster for which your database has been provisioned.
If you're using Ruby, you'll need to install the `mysql2` gem in order to connect to ClearDB's MySQL database service.
Preparing to use ClearDB once your application has been deployed to Heroku is as easy as simply setting up your application to use MySQL. To reference how to connect to MySQL from your framework, please consult your framework's documentation.
To create your ClearDB database, simply type the following Heroku command:
:::term
$ heroku addons:add cleardb:ignite
-----> Adding cleardb to sharp-mountain-4005... done, v18 (free)
This will automatically provision your new ClearDB database for you and will return the database URL to access it. You can also browse the Add-On catalog for ClearDB and simply click "Add" on the ClearDB Heroku Add-On to auto-provision your database for you.
Upgrading your ClearDB database to a larger plan is as easy as running the following command:
:::term
$ heroku addons:upgrade cleardb:punch
Upgrading cleardb:punch to myapp... done.
Upgrades are performed in place; no data migration or app reconfiguration is necessary.
To configure your Rails application to use ClearDB, simply set your DATABASE_URL environment variable to use the ClearDB URL that you have been issued. Heroku should do the rest by auto-generating a new database.yml file for your application which will connect your application directly to your ClearDB database.
You can retrieve your new ClearDB database URL by issuing the following command:
:::term
$ heroku config | grep CLEARDB_DATABASE_URL
CLEARDB_DATABASE_URL => mysql://adffdadf2341:adf4234@us-cdbr-east.cleardb.com/heroku_db?reconnect=true
To set your DATABASE_URL
to the value of CLEARDB_DATABASE_URL
, simply issue the following heroku command. For example:
**Note**: if you're using the `mysql2` gem, you will need to change the `mysql://` scheme in the CLEARDB_DATABASE_URL to `mysql2://`
:::term
$ heroku config:add DATABASE_URL='mysql://adffdadf2341:adf4234@us-cdbr-east.cleardb.com/heroku_db?reconnect=true'
Adding config vars:
DATABASE_URL => mysql2://adffd...b?reconnect=true
Restarting app... done, v61.
ClearDB uses the standard MySQL approaches to connecting via Java and the Play! framework. Below are a couple of examples on how to do so.
To instantiate a JDBC connection in your code, you can use a method like this:
:::java
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("CLEARDB_DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:mysql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
You can use XML for configuring Spring to use the CLEARDB_DATABASE_URL:
:::xml
<bean class="java.net.URI" id="dbUrl">
<constructor-arg value="#{systemEnvironment['CLEARDB_DATABASE_URL']}"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="#{ 'jdbc:mysql://' + @dbUrl.getHost() + @dbUrl.getPath() }"/>
<property name="username" value="#{ @dbUrl.getUserInfo().split(':')[0] }"/>
<property name="password" value="#{ @dbUrl.getUserInfo().split(':')[1] }"/>
</bean>
You can use Java for configuration of the BasicDataSource to connect to ClearDB in Spring:
:::java
@Configuration
public class MainConfig {
@Bean
public BasicDataSource dataSource() throws URISyntaxException {
URI dbUri = new URI(System.getenv("CLEARDB_DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:mysql://" + dbUri.getHost() + dbUri.getPath();
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(dbUrl);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
return basicDataSource;
}
}
Connecting to ClearDB from PHP is super easy, and merely requires the parsing of the CLEARDB_DATABASE_URL to get connected, like this:
:::php
<?php
$url=parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"],1);
mysql_connect($server, $username, $password);
mysql_select_db($db);
?>
**Note**: Python/Django users will need to strip the "?reconnect=true" query string parameter from the DATABASE_URL config setting, as this is for Rails users.
When you deploy a Django application, the compile process appends the following code to your settings.py to use the DATABASE_URL environment variable:
:::python
import os
import sys
import urlparse
# Register database schemes in URLs.
urlparse.uses_netloc.append('mysql')
try:
# Check to make sure DATABASES is set in settings.py file.
# If not default to {}
if 'DATABASES' not in locals():
DATABASES = {}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
print 'Unexpected error:', sys.exc_info()
You don’t need to do anything special to configure this, the above information is purely for reference.
In order to provide a secure operating environment for your applications, we strongly recommend that you use SSL encryption using the certificates available from your ClearDB dashboard. This will ensure that the communications link between your Heroku applications and ClearDB is secure.
While we automatically generate SSL certificates for encryption purposes, the private key file must be modified in order to work with Heroku's MySQL libraries.
To begin, download your certificates from your ClearDB dashboard, then run the following command on your private key file (the file with the name "key" in it):
:::term
$ openssl rsa -in cleardb_id-key.pem -out cleardb_id-key-no-password.pem
Delete the original cleardb_id-key.pem and rename cleardb_id-key-no-password.pem to cleardb_id-key.pem (this is not required, but it makes more sense with the next step). Pass the path to the SSL certificates that you downloaded from your ClearDB dashboard as query-string parameters in the database URL, like this:
In this example, the certificates are located in your application's root directory. To specify a different directory, simply prepend the path to the certificate.
:::term
$heroku config:add DATABASE_URL='mysql2://abc1223:dfk243@us-cdbr-east.cleardb.com/my_heroku_db?sslca=cleardb-ca-cert.pem&sslcert=cleardb_id-cert.pem&sslkey=cleardb_id-key.pem&reconnect=true'
Adding config vars:
DATABASE_URL => mysql2://abc12...b?reconnect=true
Restarting app... done, v61.
At this point Heroku should do the rest with regards to rebuilding your database.yml
file and connecting you to your new ClearDB database.
While we automatically generate SSL certificates for encryption purposes, the private key file must be modified in order to work with Heroku's MySQL libraries.
To begin, download your certificates from your ClearDB dashboard, then run the following command on your private key file (the file with the name "key" in it):
:::term
$ openssl rsa -in cleardb_id-key.pem -out cleardb_id-key-no-password.pem
Unfortunately, Heroku currently does not support the use of the MySQLi PHP extension, which is required for SSL support with ClearDB. This is due to the fact that ClearDB requires both the SSL CA certificate as well as the client certificate and key pair. We will update this article upon Heroku's MySQLi support announcement.
The process of setting up SSL on MySQL via the MySQL Java Connector is available via the MySQL Java Connector SSL Documentation.
You can connect via SSL to ClearDB's MySQL service by first downloading your SSL certificates from your ClearDB dashboard and then by adding the following configuration to your app:
:::python
DATABASES['default'] = {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'my-host-goes-here',
'USER': 'my-user-goes-here',
'NAME': 'my-db-name-goes-here',
'PASSWORD': 'my-db-pass-goes-here',
'OPTIONS': {'ssl': {'ca':'/path/to/ca-cert.pem', 'cert':'/path/to/cert.pem', 'key':'/path/to/key.pem'},},
}