Communication Between Services

Today, we will introduce you a little trick of Kato-port alias.

Port alias, as the name implies, is to define an alias for the component port.

Port Alias Settings

When you enter the Port Management Page, click Use Alias to set the alias of the port, as shown in the figure below:

The Role of Port Aliases

After the port alias is defined, Kato will generate two external environment variables for the alias: port alias_HOST and port alias_PORT. For example, if the port alias is MYSQL, the corresponding environment variables are MYSQL_HOST and MYSQL_HOST.

If you notice, these two environment variables are actually the access mode of the port. Access mode=port alias_HOST:port alias_PORT. For example, if the port alias is MYSQL, the corresponding access method is MYSQL_HOST:MYSQL_PORT, which is 127.0.0.1:3306.

Another very important point is that no matter how the governance mode of the application to which the component belongs, port alias_HOST can be perceived.

In other words, as long as the component that needs to access the port depends on the component, you can easily know its access method; no matter how the application governance mode changes, the access method will change accordingly and remain correct.

Spring Components Connect to MySQL

In order to explain further, let’s take the Spring component to connect to MySQL as an example to see how Spring can easily obtain access to MySQL.

Those who are familiar with Spring may know that its configuration file can look like this:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:localhost}/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword

Some students may not be familiar with Spring, but it does not matter. We just need to know that Spring will use environment variables to render the variables in the configuration file.

As long as the Spring component depends on the MySQL component, Kato will inject the external environment variables of the MySQL component into the Spring component.

In other words, after Spring components depend on MySQL, they will automatically get the environment variables MYSQL_HOST and MYSQL_HOST. If MYSQL_HOST=127.0.0.1, MYSQL_PORT=3306, after rendering by Spring, the link address of the database becomes spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_example , so that you can access the MySQL components correctly.

Summary

Port alias is a very convenient function in the communication between Kato components. By setting an alias for the port, you can easily get the access method of the port.