In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about the use of SpringCloud-Apollo in Java, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Used in ordinary Java projects
Add the Maven dependency to Apollo Client, as shown below.
Com.ctrip.framework.apolloapollo-client1.1.0
Use API to get the configuration, as shown in the following code.
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);}}
Get the Config object through ConfigService, and the config.getProperty () method can pass in that the configuration Key,defaultValue you want to get is the default value returned when the configuration center cannot find the configuration, avoiding null pointer exceptions.
Run the above code and the output is the default value of "Zhang San". Because we haven't specified some of the necessary information that Apollo needs, including Meta Server, AppId, and Environment. Cluster may not be specified, but can be used by default.
1. Meta Server configuration
Apollo supports different configurations of applications in different environments, so you need to run the Apollo Meta Server information provided to the current environment of the Apollo client.
By default, meta server and config service are deployed in the same JVM process, so the address of meta server is the address of config service.
The quick launch package we are using currently has only one DEV environment, and the address of config service is http://localhost config service 8080, which is defined in the startup script demo.sh.
In order to enable the sample code to run directly on your readers' computers, we will configure it in 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 it is an important information to obtain configuration from the server. Similarly, there are many ways to configure APPid. We use the same way as Meta Server, which is configured in classpath:/META-INF/app.properties. The content is app.id=SampleApp.
SampleApp is displayed on the main project page of Portal. If you created a new project yourself, it is your custom 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 change, only the configuration value needs to change. Therefore, the configuration of Environment can not be configured in the project, the most commonly used are the following two configuration methods.
1) through Java System Property
You can specify the environment through the System Property env of Java.
In the Java program startup script, you can specify-Denv=YOUR-ENVIRONMENT.
If you are running a jar file, you need to note that the format is java-Denv=YOUR-ENVIRONMENT-jar xxx.jar.
Notice that key is all lowercase.
2) through the configuration file
The final recommended way is to specify env=YOUR-ENVIRONMENT through a configuration file.
For Mac/Linux, the file location is / opt/settings/server.properties.
For Windows, the file location is C:\ opt\ settings\ server.properties.
The server.properties content is env=DEV.
Similarly, in order to make the sample code easier to run on your readers' computers, we use ava System Property to specify Environment, either in the startup parameters of IDE or through code on the first line of the main method (for development demonstration purposes only, not in production environments). As shown in the specific code.
Public static void main (String [] args) {System.setProperty ("env", "DEV"); / /....}
After all the configuration is complete, we run the previous sample code again, and we can see that the output is the value we configured.
4. Listen for configuration change events
In some scenarios, we need to do some special processing when the configuration changes. For example, if you need to rebuild the connection after the database connection string changes, you can use the listening mechanism provided by API. The specific code is shown below.
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 ("found modification-configuration 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, the listening event is triggered and the output is as follows:
The namespace in which the modified data occurs is: application discovers modification-configuration key: username, original value: zhangsan, modified value: zhangsan1, operation type: used in MODIFIEDSpring Boot
First prepare a Spring Boot project and add the Maven dependency of Apollo Client. The specific code is as follows:
Com.ctrip.framework.apolloapollo-client1.1.0
Then configure the information of Apollo, and put the configuration in application.properties:
App.id=SampleAppapollo.meta= http://localhost:8080apollo.bootstrap.enabled=trueapollo.bootstrap.namespaces=application
Among them
App.id: identity information.
Apollo.meta:Meta Server (Config Service).
Apollo.bootstrap.enabled: during the bootstrap phase of project startup, configuration information is injected into the Spring container.
Apollo.bootstrap.namespaces: injects namespaces.
The environment is also specified in the main method, and the code is shown below.
@ SpringBootApplicationpublic class App {public static void main (String [] args) {/ / specified environment (for development demonstration only, not for production) System.setProperty ("env", "DEV"); SpringApplication.run (App.class, args);}} 1. Placeholder injection configuration
The Placeholder injection configuration code is shown below.
/ * user name, default is zhangsan*/@Value ("${username:zhangsan}") private String username;2. Java Config usage
The specific code for how Java Config is used is shown below.
@ Data@Configurationpublic class UserConfig {@ Value ("${username:zhangsan}") private String username;}
The specific code for using the Config configuration class injection is as follows:
@ Autowiredprivate UserConfig userConfig;3. ConfigurationProperties usage
The specific code for how to use ConfigurationProperties is shown below.
@ Data@Configuration@ConfigurationProperties (prefix = "redis.cache") public class RedisConfig {private String host;}
The configuration center only needs to add the redis.cache.host configuration item to achieve injection. The configuration content is as follows:
Redis.cache.host = 192.168.1.1
ConfigurationProperties has a disadvantage, when the value of the configuration changes, it will not automatically refresh, but need to manually implement the refresh logic, the author recommends that we do not use this method, it is more tedious.
If there is a configuration that requires a unified prefix, you can use Java Config instead.
4. Spring Annotation supports 1) @ ApolloConfig
Used to automatically inject Apollo Config objects, the code is as follows.
@ ApolloConfigprivate Config config;@GetMapping ("/ config/getUserName3") public String getUserName3 () {return config.getProperty ("username", "zhangsan");} 2) @ ApolloConfigChangeListener
Used to automatically register ConfigChangeListener, the code is as follows.
ApolloConfigChangeListenerprivate void someOnChange (ConfigChangeEvent changeEvent) {if (changeEvent.isChanged ("username")) {System.out.println ("username has been modified");}} 3) @ ApolloJsonValue
Used to automatically inject the configured JSON string as an object.
Define an entity class, as shown below.
@ Datapublic class Student {private int id;private String name;}
Object injection, the code is as follows.
@ ApolloJsonValue ("${stus: []}") private List stus
The added configuration at the backend is as follows:
Stus = [{"id": 1, "name": "jason"}] the above is how SpringCloud-Apollo is used in Java. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.