Не удалось настроить источник данных: не указан атрибут 'url' микросервиса весенней загрузки - PullRequest
1 голос
/ 08 января 2020

Я попал в проводную ситуацию,

, где я не могу получить конфигурацию источника данных с сервера конфигурации

   @SpringBootApplication
   @EnableConfigServer
   public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

Ниже приведен мой yml, который находится в моей файловой системе и называется это как demo-services-development.yml

spring:  
  datasource:
    url: jdbc:mysql://localhost:3306/genesys?useSSL=false
    username: root
    password: Durairaj90
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect

после этого я попытался получить доступ к своему серверу конфигурации из chrome http://localhost: 8888 / demo-services / development

Он возвращает конфиги источника данных как json, как показано ниже

{"name":"demo-services","profiles":["development"],"label":null,"version":null,"state":null,"propertySources":[{"name":"file:///C:/Users/USHA RAJESH/config-repo/demo-services-development.yml","source":{"spring.datasource.url":"jdbc:mysql://localhost:3306/genesys?useSSL=false","spring.datasource.username":"root","spring.datasource.password":"Durairaj90","spring.datasource.driver-class-name":"com.mysql.jdbc.Driver","spring.jpa.properties.hibernate.dialect":"org.hibernate.dialect.MySQL5Dialect"}}]}

Теперь я настроил этот сервер конфигурации для своих микросервисов с помощью следующих вещей: xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.11.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR4</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Ниже мое приложение application.properties

spring.application.name=demo-services
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888

Ниже мое основное занятие

@SpringBootApplication
public class DemoServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoServiceApplication.class, args);
    }

}

При запуске приложения я получаю исключение ниже

2020-01-08 22:24:05.722  INFO 7204 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-01-08 22:24:05.723  INFO 7204 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 13406 ms
2020-01-08 22:24:06.879 ERROR 7204 --- [  restartedMain] o.s.b.web.embedded.tomcat.TomcatStarter  : Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthIndicatorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthIndicatorRegistry]: Factory method 'healthIndicatorRegistry' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbHealthIndicator' defined in class path resource [org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthIndicator]: Factory method 'dbHealthIndicator' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2020-01-08 22:24:07.175  INFO 7204 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-01-08 22:24:07.254  WARN 7204 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2020-01-08 22:24:07.311  INFO 7204 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-08 22:24:07.322 ERROR 7204 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Пожалуйста, помогите мне избавиться от этого.

1 Ответ

1 голос
/ 08 января 2020

Когда вы используете spring-cloud-server для получения ваших свойств, вам нужно создать файл bootstrap.properties|yml. Действительно, Spring создает первый контекст и создает второй после его подключения к облачному серверу.

Итак, получите файл bootstrap.properties, содержащий:

spring.cloud.config.name=demo-services
spring.cloud.config.profile=development
spring.cloud.config.uri=http://localhost:8888

И сделайте убедитесь, что ваш клиент имеет следующую зависимость в вашем pom.xml файле:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>

При запуске вы должны увидеть некоторые журналы, например:

2020-01-08 18:21:48.754  INFO 22132 --- [  restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888

И это должно работать! Если вам нужна дополнительная информация: https://cloud.spring.io/spring-cloud-commons/multi/multi__spring_cloud_context_application_context_services.html

В вашем случае происходит то, что ваш клиент не вызывает ваш сервер, чтобы получить нужные ему свойства.

PS: Я не знаю, работает ли он со свойствами, которые вы установили в application.properties, попробуйте и дайте нам знать.

...