官术网_书友最值得收藏!

Externalizing configuration

Configuration can be any property that is likely to differ between environments or production deployments. Typical examples are queue and topic names, ports, URLs, connection and pool properties, and so on.

A deployable should not have configuration in it. A configuration should be injected from outside. This makes the deployable unit immutable as it goes through the various stages of the life cycle, such as Dev, QA, and UAT.

Let's assume we have to run our product service in different environments, where the URL differentiates the environment. Therefore, the small change we make in the request mapping is as follows:

@RequestMapping("/${env}product/{id}")
Product getProduct(@PathVariable("id") int id) {

We can inject this variable in various ways. Once injected, the value is not expected to change for the life of the deployment. The simplest is to pass it in the command-line argument. Bring up the Run Configurations dialog and in the Arguments, add the command-line parameter -env=dev/ as follows:

Now, Run the configuration. During startup, you will find the value substituted in the log statement as follows:

... Mapped "{[/dev/product/{id}]}" onto com.mycompany.product.Product com.mycompany.product.ProductService.getProduct(int) 

The configuration can also be provided through configuration files, database, operating system environment properties, and so on.

Spring applications popularly use application.properties to store a few properties such as port numbers. Recently, YAML, which is a superset of JSON, is becoming more popular due to the hierarchical definition of the properties.

Create an application.yml file in the /product/src/main/resources folder of the application and put in the following:

server: 
  port: 8081 

This tells the product service to run at port 8081 instead of the default 8080. This concept is further extended to profiles. So, it is possible to load different profiles by loading the configuration specific to the profile.

Spring Cloud Config as a project handles this well. It uses a bootstrap.yml file to get the application started up with a name and details of the source to further load the configuration. Hence, bootstrap.yml contains the application name and config server details, and then loads the respective profile configuration.

Create a bootstrap.yml file in the resources folder of the application and put in the following:

spring: 
  application: 
    name: product 

We will come back to these files when we discuss service registration later.

主站蜘蛛池模板: 安丘市| 沙田区| 珲春市| 高阳县| 平陆县| 方正县| 应城市| 元江| 彭水| 崇文区| 卢龙县| 太保市| 土默特左旗| 界首市| 东港市| 乌拉特前旗| 泗阳县| 黎城县| 汉阴县| 马山县| 苏州市| 营口市| 石泉县| 云霄县| 万全县| 长葛市| 方正县| 郎溪县| 禄丰县| 正蓝旗| 岑溪市| 承德县| 龙门县| 旬阳县| 龙胜| 西乌珠穆沁旗| 石泉县| 偏关县| 丰城市| 汨罗市| 贵阳市|