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

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.

主站蜘蛛池模板: 赤壁市| 靖边县| 廊坊市| 禄丰县| 庆云县| 宁武县| 台北县| 金堂县| 涟源市| 海口市| 简阳市| 弥勒县| 安溪县| 灵武市| 宣汉县| 山东省| 阿拉尔市| 揭西县| 锡林郭勒盟| 垣曲县| 惠来县| 碌曲县| 从化市| 鄢陵县| 康乐县| 浙江省| 桂平市| 伽师县| 沁水县| 衡南县| 故城县| 山东| 鸡泽县| 湖北省| 邳州市| 常山县| 绥棱县| 新沂市| 九台市| 磐安县| 鸡东县|