This section mainly explains how to use Apollo in ordinary Java projects and Spring Boot.
Used in ordinary Java projects
Add Maven dependency of Apollo Client. The code is as follows.
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.1.0</version> </dependency>
Use the API to obtain the configuration. The specific code is as follows.
public class App { public static void main(String[] args) { Config config = ConfigService.getAppConfig(); String key = "username"; String defaultValue = "Zhang San"; String username = config.getProperty(key, defaultValue); System.out.println("username=" + username); } }
The service object is obtained through Config.config The getproperty () method can pass in the configuration Key you want to get. defaultValue is the default value returned when the configuration center cannot find the configuration to avoid null pointer exceptions.
Run the above code, and the output is the default value "Zhang San". Because we haven't specified some necessary information required by Apollo, including Meta Server, AppId and Environment. Cluster can be used by default without specifying.
1. Meta Server configuration
Apollo supports applications with different configurations in different environments, so it is necessary to run the Apollo Meta Server information provided to the current environment of the Apollo client.
By default, the meta server and config service are deployed in the same JVM process, so the address of the meta server is the address of the config service.
At present, the QuickStart package we use only has a DEV environment, and the address of config service is http://localhost : 8080, this is already starting the script demo Defined in SH.
In order to make the sample code run directly on readers' computers, we set the configuration at classpath: / meta-inf / APP Properties. The content is Apollo meta= http://localhost : 8080.
2. APPid configuration
APPid is the identity information of the application and an important information to obtain the configuration from the server. Similarly, APPid can be configured in many ways. We use the same way as Meta Server and configure it in classpath: / meta-inf / APP Properties. The content is app id=SampleApp.
SampleApp is displayed in the project main page of Portal. If it is a new project, it is your customized AppId.
3. Environment configuration
Environment has nothing to do with the project itself. A project can be deployed in different environments. The code does not need to be changed. What needs to be changed is the configuration value. Therefore, the environment configuration cannot be configured in the project. The following two configuration methods are most commonly used.
1) Through Java System Property
- You can specify the environment through Java's System Property env.
- In the Java program startup script, you can specify - Denv=YOUR-ENVIRONMENT.
- If you are running a jar file, please note that the format is java DENV = your environment jar XXX jar.
- Note that the key is all lowercase.
2) By profile
- The last recommended way is to specify env=YOUR-ENVIRONMENT through the configuration file.
- For Mac/Linux, the file location is / opt / settings / server properties.
- For Windows, the file location is C: \ opt \ settings \ server properties.
server. The content of properties is env=DEV.
Similarly, in order to make the sample code run more conveniently on the computers of readers, we use ava System Property to specify the Environment, either in the startup parameters of IDE or in the first line of main method through code (only for development demonstration, not for production Environment). The specific code is shown in.
public static void main(String[] args) { System.setProperty("env", "DEV"); // .... }
After all configurations are completed, we run the previous example code again, and you can see that the output content is the value configured by ourselves.
4. Listen for configuration change events
In some scenarios, when the configuration changes, we need to do some special processing. For example, if you need to rebuild the connection after the database connection string changes, you can use the listening mechanism provided by the API. The specific code is as follows.
config.addChangeListener(new ConfigChangeListener() { public void onChange(ConfigChangeEvent changeEvent) { System.out.println("The namespace of the modified data is:" + changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); System.out.println( String.format("Discovery modification - to configure key: %s, Original value: %s, Modified value: %s, Operation type: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType())); } } });
When we modify the configuration in Portal, a listening event will be triggered. The output result is:
The namespace of the modified data is: application Discovery modification - to configure key: username, Original value: zhangsan, Modified value: zhangsan1, Operation type: MODIFIED
Used in Spring Boot
First, prepare a Spring Boot project and add Maven dependency of Apollo Client. The specific code is as follows:
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.1.0</version> </dependency>
Then configure the information of Apollo and put the configuration in application In properties:
app.id=SampleApp apollo.meta=http://localhost:8080 apollo.bootstrap.enabled=true apollo.bootstrap.namespaces=application
Among them,
- app.id: identity information.
- apollo.meta: Meta Server(Config Service).
- apollo.bootstrap.enabled: in the bootstrap phase of the project startup, inject configuration information into the Spring container.
- apollo.bootstrap.namespaces: inject namespaces.
The environment is also specified in the main method, and the code is as follows.
@SpringBootApplication public class App { public static void main(String[] args) { // Specified environment (for development demonstration only, not for production environment)) System.setProperty("env", "DEV"); SpringApplication.run(App.class, args); } }
1. Placeholder injection configuration
The configuration code of Placeholder injection is shown below.
/** * User name. The default value is zhangsan */ @Value("${username:zhangsan}") private String username;
2. Java Config usage
The specific code of Java Config usage is as follows.
@Data @Configuration public class UserConfig { @Value("${username:zhangsan}") private String username; }
Use the Config configuration class to inject specific codes as follows:
@Autowired
private UserConfig userConfig;
3. Usage of configurationproperties
The specific code of the usage method of ConfigurationProperties is as follows.
@Data @Configuration @ConfigurationProperties(prefix = "redis.cache") public class RedisConfig { private String host; }
The configuration center only needs to add redis cache. Host configuration item can realize injection. The configuration contents are as follows:
redis.cache.host = 192.168.1.1
ConfigurationProperties has a disadvantage. When the configured value changes, it will not be refreshed automatically, but the refresh logic needs to be implemented manually. I suggest you not to use this method, which is cumbersome.
If a configuration requires a uniform prefix, it can be replaced by Java Config.
4. Spring Annotation support
1)@ApolloConfig
It is used to automatically inject Apollo Config object. The code is as follows.
@ApolloConfig private Config config; @GetMapping("/config/getUserName3") public String getUserName3() { return config.getProperty("username", "zhangsan"); }
2)@ApolloConfigChangeListener
It is used to automatically register ConfigChangeListener. The code is as follows.
@ApolloConfigChangeListener private void someOnChange(ConfigChangeEvent changeEvent) { if(changeEvent.isChanged("username")) { System.out.println("username It has been modified"); } }
3)@ApolloJsonValue
Used to automatically inject the configured JSON string into the object.
Define an entity class. The code is as follows.
@Data public class Student { private int id; private String name; }
Object injection, the code is as follows.
@ApolloJsonValue("${stus:[]}") private List<Student> stus;
The configuration added in the background is as follows:
stus = [{"id":1,"name":"jason"}]