|
| 1 | +/* |
| 2 | + * Copyright 2018 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.cloudsql; |
| 18 | + |
| 19 | +import com.zaxxer.hikari.HikariConfig; |
| 20 | +import com.zaxxer.hikari.HikariDataSource; |
| 21 | +import java.sql.Connection; |
| 22 | +import java.sql.PreparedStatement; |
| 23 | +import java.sql.SQLException; |
| 24 | +import java.util.logging.Logger; |
| 25 | +import javax.servlet.ServletContextEvent; |
| 26 | +import javax.servlet.ServletContextListener; |
| 27 | +import javax.servlet.annotation.WebListener; |
| 28 | +import javax.sql.DataSource; |
| 29 | + |
| 30 | +@WebListener("Creates a connection pool that is stored in the Servlet's context for later use.") |
| 31 | +public class ConnectionPoolContextListener implements ServletContextListener { |
| 32 | + |
| 33 | + private static final Logger LOGGER = Logger.getLogger(IndexServlet.class.getName()); |
| 34 | + |
| 35 | + // Saving credentials in environment variables is convenient, but not secure - consider a more |
| 36 | + // secure solution such as https://cloud.google.com/kms/ to help keep secrets safe. |
| 37 | + private static final String CLOUD_SQL_INSTANCE_NAME = System.getenv("CLOUD_SQL_INSTANCE_NAME"); |
| 38 | + private static final String DB_USER = System.getenv("DB_USER"); |
| 39 | + private static final String DB_PASS = System.getenv("DB_PASS"); |
| 40 | + private static final String DB_NAME = System.getenv("DB_NAME"); |
| 41 | + |
| 42 | + private DataSource createConnectionPool() { |
| 43 | + // [START cloud_sql_postgres_connection_pool] |
| 44 | + // The configuration object specifies behaviors for the connection pool. |
| 45 | + HikariConfig config = new HikariConfig(); |
| 46 | + |
| 47 | + // Configure which instance and what database user to connect with. |
| 48 | + config.setJdbcUrl(String.format("jdbc:postgresql:///%s", DB_NAME)); |
| 49 | + config.setUsername(DB_USER); // e.g. "root", "postgres" |
| 50 | + config.setPassword(DB_PASS); // e.g. "my-password" |
| 51 | + |
| 52 | + // For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections. |
| 53 | + // See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details. |
| 54 | + config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory"); |
| 55 | + config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_INSTANCE_NAME); |
| 56 | + |
| 57 | + // ... Specify additional connection properties here. |
| 58 | + |
| 59 | + // [START_EXCLUDE] |
| 60 | + |
| 61 | + // [START cloud_sql_postgres_limit_connections] |
| 62 | + // maximumPoolSize limits the total number of concurrent connections this pool will keep. Ideal |
| 63 | + // values for this setting are highly variable on app design, infrastructure, and database. |
| 64 | + config.setMaximumPoolSize(5); |
| 65 | + // minimumIdle is the minimum number of idle connections Hikari maintains in the pool. |
| 66 | + // Additional connections will be established to meet this value unless the pool is full. |
| 67 | + config.setMinimumIdle(5); |
| 68 | + // [END cloud_sql_postgres_limit_connections] |
| 69 | + |
| 70 | + // [START cloud_sql_postgres_connection_timeout] |
| 71 | + // setConnectionTimeout is the maximum number of milliseconds to wait for a connection checkout. |
| 72 | + // Any attempt to retrieve a connection from this pool that exceeds the set limit will throw an |
| 73 | + // SQLException. |
| 74 | + config.setConnectionTimeout(10000); // 10 seconds |
| 75 | + // idleTimeout is the maximum amount of time a connection can sit in the pool. Connections that |
| 76 | + // sit idle for this many milliseconds are retried if minimumIdle is exceeded. |
| 77 | + config.setIdleTimeout(600000); // 10 minutes |
| 78 | + // [END cloud_sql_postgres_connection_timeout] |
| 79 | + |
| 80 | + // [START cloud_sql_postgres_connection_backoff] |
| 81 | + // Hikari automatically delays between failed connection attempts, eventually reaching a |
| 82 | + // maximum delay of `connectionTimeout / 2` between attempts. |
| 83 | + // [END cloud_sql_postgres_connection_backoff] |
| 84 | + |
| 85 | + // [START cloud_sql_postgres_connection_lifetime] |
| 86 | + // maxLifetime is the maximum possible lifetime of a connection in the pool. Connections that |
| 87 | + // live longer than this many milliseconds will be closed and reestablished between uses. This |
| 88 | + // value should be several minutes shorter than the database's timeout value to avoid unexpected |
| 89 | + // terminations. |
| 90 | + config.setMaxLifetime(1800000); // 30 minutes |
| 91 | + // [END cloud_sql_postgres_connection_lifetime] |
| 92 | + |
| 93 | + // [END_EXCLUDE] |
| 94 | + |
| 95 | + // Initialize the connection pool using the configuration object. |
| 96 | + DataSource pool = new HikariDataSource(config); |
| 97 | + // [END cloud_sql_postgres_connection_pool] |
| 98 | + return pool; |
| 99 | + } |
| 100 | + |
| 101 | + private void createTable(DataSource pool) throws SQLException { |
| 102 | + // Safely attempt to create the table schema. |
| 103 | + try (Connection conn = pool.getConnection()) { |
| 104 | + PreparedStatement createTableStatement = conn.prepareStatement( |
| 105 | + "CREATE TABLE IF NOT EXISTS votes ( " |
| 106 | + + "vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL, candidate CHAR(6) NOT NULL," |
| 107 | + + " PRIMARY KEY (vote_id) );" |
| 108 | + ); |
| 109 | + createTableStatement.execute(); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + @Override |
| 114 | + public void contextDestroyed(ServletContextEvent event) { |
| 115 | + // This function is called when the Servlet is destroyed. |
| 116 | + HikariDataSource pool = (HikariDataSource) event.getServletContext().getAttribute("my-pool"); |
| 117 | + if (pool != null) { |
| 118 | + pool.close(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + @Override |
| 123 | + public void contextInitialized(ServletContextEvent event) { |
| 124 | + // This function is called when the application starts and will safely create a connection pool |
| 125 | + // that can be used to connect to. |
| 126 | + DataSource pool = (DataSource) event.getServletContext().getAttribute("my-pool"); |
| 127 | + if (pool == null) { |
| 128 | + pool = createConnectionPool(); |
| 129 | + event.getServletContext().setAttribute("my-pool", pool); |
| 130 | + } |
| 131 | + try { |
| 132 | + createTable(pool); |
| 133 | + } catch (SQLException ex) { |
| 134 | + throw new RuntimeException("Unable to verify table schema. Please double check the steps" |
| 135 | + + "in the README and try again.", ex); |
| 136 | + } |
| 137 | + } |
| 138 | +} |
0 commit comments