jhipster框架學習(三)

JHipster配置文件介紹

jhipster生成的微服務項目通常有多個配置文件,比如:application-dev.yml,application-prod.yml,application.yml,bootstrap.yml,bootstrap-prod.yml。那麼一個項目中有這麼多配置文件,在啓動的時候到底是如何加載配置信息的呢?下面我們來一點點的分析。

    首先,很明顯的名稱後面帶有dev字母的表示存儲開發環境的配置信息,名稱後面帶有prod字母的表示存儲生產環境的配置信息。通過簡單的分類之後,接下來我們只需要分析其中一類就好了,這裏我們以含有dev名稱的配置文件爲例進行分析。

bootstrap.yml文件

    bootstrap.yml指的是開發環境的配置文件,bootstrap-prod.yml則指的是生產環境的配置文件。那bootstrap.yml文件是什麼呢?我們先來看一下這個文件的介紹:

要說bootstrap文件,先要從spring cloud說起,畢竟JHipster這個開發平臺只是把spring cloud整合到自己的平臺上。在spring cloud中有一個“引導上下文”的概念,這是主應用程序的父上下文。引導上下文負責從配置服務器加載配置屬性,以及解密外部配置文件中的屬性。和主應用程序加載application.*(yml或properties)中的屬性不同,引導上下文加載bootstrap.*中的屬性。配置在bootstrap.*中的屬性有更高的優先級,因此默認情況下它們不能被本地配置文件覆蓋。如需禁用引導過程,可設置spring.cloud.bootstrap.enabled=false。

總之,在JHipster中項目啓動時總是先加載bootstrap.yml文件,然後再加載其他的配置文件,並且該文件的內容不會被覆蓋。那麼我們來看看bootstrap文件中的內容吧:

1.user微服務的bootstrap.yml文件

# ===================================================================
# Spring Cloud Config bootstrap configuration for the "dev" profile
# In prod profile, properties will be overwriten by the ones defined in bootstrap-prod.yml
# ===================================================================

jhipster:
    registry:
        password: admin   #user微服務註冊到registry服務中心的密碼是admin

spring:                   #user微服務的項目名稱
    application:
        name: user
    profiles:            #user微服務啓動時指定加載dev配置文件還是prod配置文件,這裏我們不指定
        # The commented value for `active` can be replaced with valid Spring profiles to load.
        # Otherwise, it will be filled in by maven when building the WAR file
        # Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS`
        active: #spring.profiles.active#
    cloud:               #這段配置是指將user微服務的配置文件交給註冊中心registry裏面的config servier管理
        config:          #user微服務首先去registy中的config目錄下加載自己的配置文件(文件名是name-profile.yml,即user-dev.yml)
                         #如果registry中獲取配置文件的方式是從git上獲取,那麼這裏的label:master就是指定user微服務獲取哪個分支上的配置文件             
            fail-fast: true   #JHipster整合了Netflix的Hystrix(一個實現了超時機制和斷路器模式的工具類庫),這裏是指是否開啓快速失敗機制,通常選擇true
            uri: http://admin:${jhipster.registry.password}@localhost:8761/config
            # name of the config server's property source (file.yml) that we want to use
            name: user
            profile: dev # profile(s) of the property source
            label: master # toggle to switch to a different version of the configuration as stored in git
            # it can be set to any label, branch or commit of the config source git repository

info:                  #自行設置user微服務的版本,此處未設置
    project:
        version: #project.version#
2.註冊中心registry的bootstray.yml配置文件

# ===================================================================
# Spring Cloud Config bootstrap configuration for the "dev" profile
# In prod profile, properties will be overwriten by the ones defined in bootstrap-prod.yml
# ===================================================================

spring:                              #註冊中心的應用名稱
    application:
        name: jhipster-registry
    profiles:                       #此處是指加載配置文件方式:dev類型的文件,native本地加載,(git遠程加載)
        active: dev,native
    cloud:          #這裏是對registry中的spring cloud config進行配置,如果active包含native則所有項目的配置文件都只從本地加載,
        config:     #如果active包含git則所有配置文件都從git倉庫中加載,uri指定了git倉庫的地址,prefix是指搜索配置文件在git倉庫中的               
            server: #路徑,由於我把配置文件都放在git倉庫的config文件夾下,所以需要這樣配置 
                git: #剩下的配置屬性和user微服務的屬性雷同,就不再一一介紹了。
                    uri: https://git.oschina.net/liupengf/profiles
                native:
                    search-locations: file:./central-config
                prefix: /config
                bootstrap: true
            fail-fast: true
            # name of the config server's property source (file.yml) that we want to use
            name: jhipster-registry
            profile: dev # profile(s) of the property source
            label: master # toggle to switch to a different version of the configuration as stored in git
            # it can be set to any label, branch or commit of the config source git repository

info:
    project:
        version: #project.version#

# uncomment to enable encryption features
encrypt:    #這個屬性是配置加解密的key,由於配置文件中有些敏感信息如數據庫密碼等不方便放在git倉庫中,所以需要加解密。
    key: my-secret-encryption-key-to-change-in-production
到這裏爲止,有關bootstrap.yml中的相關屬性都介紹完了,其中紅色的註解是我對配置屬性的理解。

對於微服務user來說,在項目啓動時加載完之後會去加載哪個配置文件呢?

這裏要分兩種情況,如果registry註冊中心bootstrap配置文件中spring.profile.active:指定native,則user微服務就會加載本地的配置文件,如果指定的是git,則會去git倉庫中加載user-dev|prod.yml。

假定是從本地加載配置文件,我們先來看一下user微服務的application.yml配置文件:

# ===================================================================
# Spring Boot configuration.
#
# This configuration will be overriden by the Spring profile you use,
# for example application-dev.yml if you use the "dev" profile.
#
# More information on profiles: https://jhipster.github.io/profiles/
# More information on configuration properties: https://jhipster.github.io/common-application-properties/
# ===================================================================

# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================

eureka:
    client:
        enabled: true
        healthcheck:
            enabled: true
        fetch-registry: true
        register-with-eureka: true
        instance-info-replication-interval-seconds: 10
        registry-fetch-interval-seconds: 10
    instance:
        appname: user
        instanceId: user:${spring.application.instance-id:${random.value}}
        lease-renewal-interval-in-seconds: 5
        lease-expiration-duration-in-seconds: 10
        status-page-url-path: ${management.context-path}/info
        health-check-url-path: ${management.context-path}/health
        metadata-map:
            profile: ${spring.profiles.active}
            version: ${info.project.version}
ribbon:
    eureka:
        enabled: true
# See https://github.com/Netflix/Hystrix/wiki/Configuration
#hystrix:
#    command:
#        default:
#            execution:
#                isolation:
#                    thread:
#                        timeoutInMilliseconds: 10000

management:
    security:
        roles: ADMIN
    context-path: /management
    health:
        mail:
            enabled: false # When using the MailService, configure an SMTP server and set this to true
spring:
    application:
        name: user
    jackson:
        serialization.write_dates_as_timestamps: false
    jpa:
        open-in-view: false
        hibernate:
            ddl-auto: none
            naming:
                physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
                implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
    messages:
        basename: i18n/messages
    mvc:
        favicon:
            enabled: false
    thymeleaf:
        mode: XHTML

security:
    basic:
        enabled: false

server:
    session:
        cookie:
            http-only: true


# ===================================================================
# JHipster specific properties
#
# Full reference is available at: https://jhipster.github.io/common-application-properties/
# ===================================================================

jhipster:
    async:
        core-pool-size: 2
        max-pool-size: 50
        queue-capacity: 10000
    # By default CORS is disabled. Uncomment to enable.
    #cors:
        #allowed-origins: "*"
        #allowed-methods: GET, PUT, POST, DELETE, OPTIONS
        #allowed-headers: "*"
        #exposed-headers:
        #allow-credentials: true
        #max-age: 1800
    mail:
        from: user@localhost
    swagger:
        default-include-pattern: /api/.*
        title: user API
        description: user API documentation
        version: 0.0.1
        terms-of-service-url:
        contact-name:
        contact-url:
        contact-email:
        license:
        license-url:
    ribbon:
        display-on-active-profiles: dev

# ===================================================================
# Application specific properties
# Add your own application properties here, see the ApplicationProperties class
# to have type-safe configuration, like in the JHipsterProperties above
#
# More documentation is available at:
# https://jhipster.github.io/common-application-properties/
# ===================================================================

application:
關於application.yml這個配置文件裏面的屬性我並不是完全都瞭解,所以我就在這裏統一總結一下:這個配置文件中通常會放一些公共的配置信息,一般情況下不需要修改,比如eureka設置的相關信息、ribbon配置以及Restful風格的相關設置。但是這個配置文件中的信息會被application-dev|prod.yml中的內容所替換,所以需要修改的配置我們通常定義在application-dev|prod.yml中。

下面來看一下user微服務的application-dev.yml的配置信息:

# ===================================================================
# Spring Boot configuration for the "dev" profile.
#
# This configuration overrides the application.yml file.
#
# More information on profiles: https://jhipster.github.io/profiles/
# More information on configuration properties: https://jhipster.github.io/common-application-properties/
# ===================================================================

# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================

eureka:    #eureka的相關設置,設置註冊到eureka的默認地址上http://admin:${jhipster.registry.password}@localhost:8761/eureka/
    instance:
        prefer-ip-address: true  #指定微服務在服務中心的instansId
        instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}:${random.value}
    client:
        service-url:
            defaultZone: http://admin:${jhipster.registry.password}@localhost:8761/eureka/

spring:      #指定啓動的配置文件類型
    profiles:
        active: dev
        include: no-liquibase,swagger
    devtools:
        restart:
            enabled: true
        livereload:
            enabled: false # we use gulp + BrowserSync for livereload
    jackson:
        serialization.indent_output: true
    datasource:  #配置數據庫相關的信息
        type: com.zaxxer.hikari.HikariDataSource
        url: jdbc:mysql://127.0.0.1:3306/jhipster?useUnicode=true&characterEncoding=utf8&characterResultSets=utf8
        username: root
        password: root
        hikari:
            data-source-properties:
                cachePrepStmts: true
                prepStmtCacheSize: 250
                prepStmtCacheSqlLimit: 2048
                useServerPrepStmts: true
    jpa:
        database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
        database: MYSQL
        show-sql: true
        generate-ddl: true
        properties:
            hibernate.id.new_generator_mappings: true
            hibernate.cache.use_second_level_cache: true
            hibernate.cache.use_query_cache: false
            hibernate.generate_statistics: true
            hibernate.cache.region.factory_class: com.hazelcast.hibernate.HazelcastCacheRegionFactory
            hibernate.cache.hazelcast.instance_name: user
            hibernate.cache.use_minimal_puts: true
            hibernate.cache.hazelcast.use_lite_member: true
    mail:
        host: localhost
        port: 25
        username:
        password:
    messages:
        cache-seconds: 1
    thymeleaf:
        cache: false
    zipkin: # Use the "zipkin" Maven profile to have the Spring Cloud Zipkin dependencies
        base-url: http://localhost:9411
        enabled: false
        locator:
            discovery:
                enabled: true

liquibase:
    contexts: dev

# ===================================================================
# To enable SSL, generate a certificate using:
# keytool -genkey -alias user -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
#
# You can also use Let's Encrypt:
# https://maximilian-boehm.com/hp2121/Create-a-Java-Keystore-JKS-from-Let-s-Encrypt-Certificates.htm
#
# Then, modify the server.ssl properties so your "server" configuration looks like:
#
# server:
#    port: 8443
#    ssl:
#        key-store: keystore.p12
#        key-store-password: <your-password>
#        keyStoreType: PKCS12
#        keyAlias: user
# ===================================================================
server:  #設置端口號
    port: 8081

# ===================================================================
# JHipster specific properties
#
# Full reference is available at: https://jhipster.github.io/common-application-properties/
# ===================================================================

jhipster:
    http:
        version: V_1_1 # To use HTTP/2 you will need SSL support (see above the "server.ssl" configuration)
    cache: # Cache configuration
        hazelcast: # Hazelcast distributed cache
            time-to-live-seconds: 3600
            backup-count: 1
    # CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
    cors:
        allowed-origins: "*"
        allowed-methods: GET, PUT, POST, DELETE, OPTIONS
        allowed-headers: "*"
        exposed-headers:
        allow-credentials: true
        max-age: 1800
    security:
        authentication:
            jwt:
                secret: my-secret-token-to-change-in-production
                # Token is valid 24 hours
                token-validity-in-seconds: 86400
                token-validity-in-seconds-for-remember-me: 2592000
    mail: # specific JHipster mail property, for standard properties see MailProperties
        from: user@localhost
        base-url: http://127.0.0.1:8081
    metrics: # DropWizard Metrics configuration, used by MetricsConfiguration
        jmx.enabled: true
        graphite: # Use the "graphite" Maven profile to have the Graphite dependencies
            enabled: false
            host: localhost
            port: 2003
            prefix: user
        prometheus: # Use the "prometheus" Maven profile to have the Prometheus dependencies
            enabled: false
            endpoint: /prometheusMetrics
        logs: # Reports Dropwizard metrics in the logs
            enabled: false
            report-frequency: 60 # in seconds
    logging:
        logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration
            enabled: false
            host: localhost
            port: 5000
            queue-size: 512
        spectator-metrics: # Reports Spectator Circuit Breaker metrics in the logs
            enabled: false
            # edit spring.metrics.export.delay-millis to set report frequency

# ===================================================================
# Application specific properties
# Add your own application properties here, see the ApplicationProperties class
# to have type-safe configuration, like in the JHipsterProperties above
#
# More documentation is available at:
# https://jhipster.github.io/common-application-properties/
# ===================================================================

application:
可以看到,application-dev.yml中的配置信息我也只是挑了一些簡單的部分註釋了一下,這個文件中有些內容和appliaction.yml中是重合的,不過並無大礙。
目前我對JHipster的配置文件的瞭解就只有這麼多了,如果以後還有更多的瞭解再繼續更新,今天就到這裏吧。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章