Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of dynamically switching data sources in SpringBoot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What is the method of dynamically switching data sources in SpringBoot? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

In fact, this representation is not quite right, it should be a method for Druid to dynamically switch data sources, but it has been applied in the springboot framework, and the code has been prepared for a long time. Before using it in a database migration, it is found that Druid is still very powerful and is very convenient for dynamic data source switching.

First of all, the scenario here is a little different from what I used originally. In the project, we use the configuration center to control the data source switch, unified switching, and here's an example that can be configured according to the interface annotations.

The first part is the core, how to achieve data source switching based on Spring JDBC and Druid, inherits the class org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource, his determineCurrentLookupKey method will be called to get the object used to determine which data source to choose, that is, lookupKey, you can also see through this class is through this lookupKey route to find the data source.

Public class DynamicDataSource extends AbstractRoutingDataSource {@ Override protected Object determineCurrentLookupKey () {if (DatabaseContextHolder.getDatabaseType ()! = null) {return DatabaseContextHolder.getDatabaseType () .getName ();} return DatabaseType.MASTER1.getName ();}}

And how to use this lookupKey involves our DataSource configuration. It turns out that we can configure the data source directly through spring's jdbc, like this.

Now we are going to use Druid as the data source, then configure the parameters of DynamicDataSource, and select the corresponding DataSource through key, that is, the master1 and master2 configured below

Now let's go back to the head and introduce the DatabaseContextHolder. Here we use ThreadLocal to store the DatabaseType. Why do we use this because we want to configure different data sources at the interface level, and to isolate the holders from each other, we use ThreadLocal. About it, you can also see an article I wrote earlier to talk about the legendary ThreadLocal, and DatabaseType is a simple enumeration.

Public class DatabaseContextHolder {public static final ThreadLocal databaseTypeThreadLocal = new ThreadLocal (); public static DatabaseType getDatabaseType () {return databaseTypeThreadLocal.get ();} public static void putDatabaseType (DatabaseType databaseType) {databaseTypeThreadLocal.set (databaseType);} public static void clearDatabaseType () {databaseTypeThreadLocal.remove ();}} public enum DatabaseType {MASTER1 ("master1", "1"), MASTER2 ("master2", "2"); private final String name Private final String value; DatabaseType (String name, String value) {this.name = name; this.value = value;} public String getName () {return name;} public String getValue () {return value;} public static DatabaseType getDatabaseType (String name) {if (MASTER2.name.equals (name)) {return MASTER2;} return MASTER1 }}

You can see here that the data source is switched by dynamically setting lookupKey through putDatabaseType. If you want to set it through interface annotation configuration, we need an annotation.

Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.METHOD) public @ interface DataSource {String value ();}

This annotation can be configured on my interface method, such as this

Public interface StudentService {@ DataSource ("master1") public Student queryOne (); @ DataSource ("master2") public Student queryAnother ();}

Set up the data source through the section

@ Aspect@Component@Order (- 1) public class DataSourceAspect {@ Pointcut ("execution (* com.nicksxs.springdemo.service..*.* (..)") Public void pointCut () {} @ Before ("pointCut ()") public void before (JoinPoint point) {Object target = point.getTarget (); System.out.println (target.toString ()); String method = point.getSignature (). GetName (); System.out.println (method); Class [] classz = target.getClass (). GetInterfaces () Class [] parameterTypes = ((MethodSignature) point.getSignature ()) .getMethod () .getParameterTypes (); try {Method m = classz [0] .getMethod (method, parameterTypes); System.out.println ("method" + m.getName ()); if (m.isAnnotationPresent (DataSource.class)) {DataSource data = m.getAnnotation (DataSource.class) System.out.println ("dataSource:" + data.value ()); DatabaseContextHolder.putDatabaseType (DatabaseType.getDatabaseType (data.value ();}} catch (Exception e) {e.printStackTrace ();}} @ After ("pointCut ()") public void after () {DatabaseContextHolder.clearDatabaseType ();}}

Use the API to determine whether there are annotations and the values of annotations. The configuration of DatabaseType is not very good, but it is ignored first, and then cleaned up after the pointcut.

This is my master1 data.

Master2's data.

Then run a simple demo.

@ Overridepublic void run (String...args) {LOGGER.info ("run here"); System.out.println (studentService.queryOne ()); System.out.println (studentService.queryAnother ());}

Take a look at the running results.

In fact, the application scenario of this method can not only be used to migrate the database, but also achieve fine separation of read and write data sources and so on, which can be regarded as a simple record and sharing.

After reading the above, have you mastered the method of dynamically switching data sources in SpringBoot? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report