Не удается подключиться к postgres в docker - PullRequest
0 голосов
/ 17 апреля 2020

Я начал Postgres в Docker. Работает нормально. Я зашла внутрь docker контейнера через bash и проверила, работает ли БД. Цель состоит в том, чтобы связать его с приложением spring mvc без пружинной загрузки. Если я правильно понял, проблема заключается в связи с Postgres. Приложение не может подключиться к идентификатору. Как это исправить? Приложение собирается и запускается правильно. Запрос на получение запроса работает нормально, но когда я пытаюсь опубликовать сообщение, оно не работает.

Я попытался использовать два разных источника данных: если я отправляю сообщение, я вижу ошибку в браузере:

1 .

@Bean
public DataSource dataSource() {
    DriverManagerDataSource driver = new DriverManagerDataSource();
    driver.setDriverClassName("org.postgresql.Driver");
    driver.setUrl("jdbc:postgresql://localhost:6000/users");
    driver.setUsername("postgres");
    driver.setPassword("task1");
    return driver;
}

Ошибка:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
@Bean
public DataSource dataSource() throws PropertyVetoException {
    ComboPooledDataSource driver = new ComboPooledDataSource();
    driver.setDriverClass("org.postgresql.Driver");
    driver.setJdbcUrl("jdbc:postgresql://localhost:6000/users");
    driver.setUser("postgres");
    driver.setPassword("task1");
    return driver;
}

Эта ошибка отображается в консоли при запуске приложения:

17-Apr-2020 19:26:58.016 WARNING [C3P0PooledConnectionPoolManager[identityToken->z8kfsxa912030ejmgd6af|6144d891]-HelperThread-#2] com.mchange.v2.resourcepool.BasicResourcePool. Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@46e95772 is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
17-Apr-2020 19:26:58.011 WARNING [C3P0PooledConnectionPoolManager[identityToken->z8kfsxa912030ejmgd6af|6144d891]-HelperThread-#1] com.mchange.v2.resourcepool.BasicResourcePool. com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@628b9aa1 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: 
    org.postgresql.util.PSQLException: The connection attempt failed.

Стандарт Docker Файл:

FROM postgres

ENV POSTGRES_USER task1
ENV POSTGRES_PASSWORD task1
ENV POSTGRES_DB users

и docker -составить:

version: "3.7"
services:
  postgres:
    build:
      context: .
      dockerfile: db.Dockerfile
    image: postgrei
    container_name: DB
    ports:
    - 6000:6000

Другой код:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.repository")
@ComponentScan(basePackages = "com.task1")
public class DataJpaConfig {



    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource driver = new ComboPooledDataSource();
        driver.setDriverClass("org.postgresql.Driver");
        driver.setJdbcUrl("jdbc:postgresql://localhost:6000/users");
        driver.setUser("postgres");
        driver.setPassword("task1");
        return driver;
    }


    @Bean
    public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        return new HibernateJpaVendorAdapter();
    }

    @Bean
    public Properties hibernateProperties() {
        Properties hibernateProp = new Properties();
        hibernateProp.put("hibernate.dialect",
                "org.hibernate.dialect.PostgreSQL95Dialect");
        hibernateProp.put("hibernate.format sql", true);
        hibernateProp.put("hibernate.use sql comments", true);
        hibernateProp.put("hibernate.show_sql", true);
        hibernateProp.put("hibernate.max_fetch_depth", 3);
        hibernateProp.put("hibernate.jdbc.batch_size", 10);
        hibernateProp.put("hibernate.jdbc.fetch_size", 50);
        return hibernateProp;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factoryBean =
        new LocalContainerEntityManagerFactoryBean();
        factoryBean.setPackagesToScan(
                "com.task1");
        try {
            factoryBean.setDataSource(dataSource());
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        factoryBean.setJpaVendorAdapter(
                new HibernateJpaVendorAdapter());
        factoryBean.setJpaProperties(hibernateProperties());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        factoryBean.afterPropertiesSet();
        return factoryBean.getNativeEntityManagerFactory();
    }

}


public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{DataJpaConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{ApplicationConfiguration.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}


@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = "com.task1")
public class ApplicationConfiguration implements WebMvcConfigurer {}

журналы из docker контейнер:

The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/data ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Etc/UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok


Success. You can now start the database server using:

    pg_ctl -D /var/lib/postgresql/data -l logfile start

initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.
waiting for server to start....2020-04-17 16:17:52.683 UTC [47] LOG:  starting PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2020-04-17 16:17:52.684 UTC [47] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2020-04-17 16:17:52.698 UTC [48] LOG:  database system was shut down at 2020-04-17 16:17:50 UTC
2020-04-17 16:17:52.702 UTC [47] LOG:  database system is ready to accept connections
 done
server started
CREATE DATABASE


/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/createUserTable.sql
CREATE TABLE


/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/putDataToUserTable.sql
INSERT 0 3


waiting for server to shut down...2020-04-17 16:17:53.317 UTC [47] LOG:  received fast shutdown request
.2020-04-17 16:17:53.332 UTC [47] LOG:  aborting any active transactions
2020-04-17 16:17:53.335 UTC [47] LOG:  background worker "logical replication launcher" (PID 54) exited with exit code 1
2020-04-17 16:17:53.335 UTC [49] LOG:  shutting down
2020-04-17 16:17:53.407 UTC [47] LOG:  database system is shut down
 done
server stopped

PostgreSQL init process complete; ready for start up.

2020-04-17 16:17:53.431 UTC [1] LOG:  starting PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2020-04-17 16:17:53.432 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2020-04-17 16:17:53.432 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2020-04-17 16:17:53.441 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2020-04-17 16:17:53.454 UTC [83] LOG:  database system was shut down at 2020-04-17 16:17:53 UTC
2020-04-17 16:17:53.458 UTC [1] LOG:  database system is ready to accept connections

1 Ответ

1 голос
/ 17 апреля 2020

Проблема в файле docker -compose.yml. Вам необходимо сопоставить порт базы данных. Измените порты с 6000:6000 на 6000:5432, а затем docker-compose down и docker-compose up.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...