Spring cloud config implements hot deployment of datasource, clouddatasource

Source: Internet
Author: User

Spring cloud config implements hot deployment of datasource, clouddatasource

The basic usage of spring cloud config has been mentioned in the previous blog. If you do not know about it, read the previous blog first.

Spring cloud config integrates gitlab to build a distributed configuration Center

High Availability of spring cloud config distributed configuration Center

Today, we focus on how to implement hot data source deployment.

1. Configure the data source on the client

@ RefreshScope @ Configuration // configure the data source public class performanceconfigure {@ Bean @ RefreshScope // refresh the Configuration file @ ConfigurationProperties (prefix = "spring. datasource ") // The prefix automatically configured for the Data Source: public DataSource dataSource () {return performancebuilder. create (). build ();}}

Through the above steps, you can modify the configuration file on gitlab. After refreshing, the server does not need to be restarted, and the new data source will take effect.

2. Hot deployment of Custom Data sources

When we use spring boot to integrate druid, We need to manually configure the data source. The Code is as follows:

Package com. chhliu. springcloud. config; import java. SQL. SQLException; import javax. SQL. dataSource; import org. springframework. beans. factory. annotation. value; import org. springframework. cloud. context. config. annotation. refreshScope; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. configuration; import org. springframework. context. annotation. primary; imp Ort com. alibaba. druid. pool. druidDataSource; import lombok. extern. slf4j. slf4j;/*** Description: if you do not use code to manually initialize DataSource, SQL monitoring on the monitoring interface will have no data ("is a spring boot bug ??? ") * @ Author chhliu * Creation Time: 7:33:08, January 1, February 9, 2017 * @ version 1.2.0 */@ Slf4j @ Configuration @ RefreshScope public class DruidConfiguration {@ Value (" $ {spring. datasource. url} ") private String dbUrl; @ Value (" $ {spring. datasource. username} ") private String username; @ Value (" $ {spring. datasource. password} ") private String password; @ Value (" $ {spring. datasource. driverClassName} ") private String driverClassName; @ Value (" $ {spring. datasource. initialSize} ") private int initialSize; @ Value (" $ {spring. datasource. minIdle} ") private int minIdle; @ Value (" $ {spring. datasource. maxActive} ") private int maxActive; @ Value (" $ {spring. datasource. maxWait} ") private int maxWait; @ Value (" $ {spring. datasource. timeBetweenEvictionRunsMillis} ") private int timeBetweenEvictionRunsMillis; @ Value (" $ {spring. datasource. minEvictableIdleTimeMillis} ") private int minEvictableIdleTimeMillis; @ Value (" $ {spring. datasource. validationQuery} ") private String validationQuery; @ Value (" $ {spring. datasource. testWhileIdle} ") private boolean testWhileIdle; @ Value (" $ {spring. datasource. testOnBorrow} ") private boolean testOnBorrow; @ Value (" $ {spring. datasource. testOnReturn} ") private boolean testOnReturn; @ Value (" $ {spring. datasource. poolPreparedStatements} ") private boolean poolPreparedStatements; @ Value (" $ {spring. datasource. maxPoolPreparedStatementPerConnectionSize} ") private int maxPoolPreparedStatementPerConnectionSize; @ Value (" $ {spring. datasource. filters} ") private String filters; @ Value (" $ {spring. datasource. connectionProperties} ") private String connectionProperties; @ Value (" $ {spring. datasource. useglobalperformancestat} ") private boolean useglobalperformancestat; @ Bean // declare it as a Bean instance @ Primary // In the same DataSource, first use the labeled DataSource @ RefreshScope public DataSource () {DruidDataSource datasource = new DruidDataSource (); datasource. setUrl (this. dbUrl); datasource. setUsername (username); datasource. setPassword (password); datasource. setDriverClassName (driverClassName); // configuration datasource. setInitialSize (initialSize); datasource. setMinIdle (minIdle); datasource. setMaxActive (maxActive); datasource. setMaxWait (maxWait); datasource. setTimeBetweenEvictionRunsMillis (timeBetweenEvictionRunsMillis); datasource. setMinEvictableIdleTimeMillis (minEvictableIdleTimeMillis); datasource. setValidationQuery (validationQuery); datasource. setTestWhileIdle (testWhileIdle); datasource. setTestOnBorrow (testOnBorrow); datasource. setTestOnReturn (testOnReturn); datasource. setPoolPreparedStatements (poolPreparedStatements); datasource. setMaxPoolPreparedStatementPerConnectionSize (maxPoolPreparedStatementPerConnectionSize); datasource. setuseglobalperformancestat (useglobalperformancestat); try {datasource. setFilters (filters);} catch (SQLException e) {log. error ("druid configuration initialization filter:" + e);} datasource. setConnectionProperties (connectionProperties); return datasource ;}}

The above example can also be used to dynamically refresh the data source. Next, let's take a look at how spring cloud config implements hot data source deployment.

From the previous blog, it is not difficult to find that to achieve dynamic refresh, the key point is the post refresh request, and we will start from refreshing the configuration file.
When we refresh the post request, the request will be intercepted by the actuator module. This can be seen from the startup log file.

Copy codeThe Code is as follows:
Mapped "{[/refresh |/refresh. json], methods = [POST]} "onto public java. lang. object org. springframework. cloud. endpoint. genericPostableMvcEndpoint. invoke ()

Next, let's look at the EndPoint defined by actuator, and then we find the RefreshEndpoint class. The source code of this class is as follows:

@ConfigurationProperties(prefix = "endpoints.refresh", ignoreUnknownFields = false) @ManagedResource public class RefreshEndpoint extends AbstractEndpoint<Collection<String>> {    private ContextRefresher contextRefresher;    public RefreshEndpoint(ContextRefresher contextRefresher) {     super("refresh");     this.contextRefresher = contextRefresher;   }    @ManagedOperation   public String[] refresh() {     Set<String> keys = contextRefresher.refresh();     return keys.toArray(new String[keys.size()]);   }    @Override   public Collection<String> invoke() {     return Arrays.asList(refresh());   }  } 

From the source code above, we can see that the focus is on the ContextRefresher class. Because this class is too long, some source code of this class will be pasted below:

Private RefreshScope scope; public ContextRefresher (ConfigurableApplicationContext context, RefreshScope scope) {this. context = context; this. scope = scope;} public synchronized Set <String> refresh () {Map <String, Object> before = extract (this. context. getEnvironment (). getPropertySources (); // 1. before: load and extract the configuration file addConfigFilesToEnvironment (); // 2. Load the configuration file to the environment Set <String> keys = changes (before, extract (this. context. getEnvironment (). getPropertySources ())). keySet (); // 3. Replace the value of this in the original environment variable. context. publishEvent (new EnvironmentChangeEvent (keys); // 4. Release a change event, this. scope. refreshAll (); return keys ;}

From the above Code, it is not difficult to see that the focus has gone through four steps, which have been marked in the above Code.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.