In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "spring-boot combined with AOP to achieve dynamic configuration of data sources", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "spring-boot combined with AOP to achieve data source dynamic configuration method" it!
Realization of multiple data source switching in Spring-Boot+AOP mode
The overall design idea: Spring-Boot+AOP mode to achieve multi-data source switching, inheriting AbstractRoutingDataSource to achieve dynamic acquisition of data sources, in the service layer using annotations to specify data sources.
I. multiple data source configuration
In application.properties, our configuration looks like this
# Master data source druid.master.url=jdbc:mysql://url/masterdb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNulldruid.master.username=xxxdruid.master.password=123druid.master.driver-class-name=com.mysql.jdbc.Driverdruid.master.max-wait=5000druid.master.max-active=100druid.master.test-on-borrow=truedruid.master.validation-query=SELECT slave data source druid.slave.url=jdbc:mysql://url/slavedb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNulldruid.slave.username=xxxdruid.slave.password=123druid.slave.driver-class-name=com.mysql.jdbc.Driverdruid. Slave.max-wait=5000druid.slave.max-active=100druid.slave.test-on-borrow=truedruid.slave.validation-query=SELECT 1
Read configuration
2. Dynamic data sources
Spring provides us with AbstractRoutingDataSource, a data source with routing. After inheritance, we need to implement its determineCurrentLookupKey (), which is used to customize the routing method of the actual data source name, and since we have saved the information in ThreadLocal, we just need to take it out of it.
Public class DynamicDataSource extends AbstractRoutingDataSource {private Logger logger = LoggerFactory.getLogger (this.getClass ()); @ Override protected Object determineCurrentLookupKey () {String dataSource = JdbcContextHolder.getDataSource (); logger.info ("data source is {}", dataSource); return dataSource;}} three. Dynamic switching classes for data sources
Dynamic data source switching is based on AOP, so we need to declare an AOP aspect, switch the data source before the cut, and remove the data source name after the section is completed.
@ Aspect@Order (1) / / sets the AOP execution order (it needs to be before the transaction, otherwise the transaction only occurs in the default library) @ Componentpublic class DataSourceAspect {private Logger logger = LoggerFactory.getLogger (this.getClass ()); / / pointcut @ Pointcut ("execution (* com.xxx.service.*.* (..)")) Public void aspect () {} @ Before ("aspect ()") private void before (JoinPoint point) {Object target = point.getTarget (); String method = point.getSignature () .getName (); Class classz = target.getClass (); / / get the target class Class [] parameterTypes = ((MethodSignature) point.getSignature ()) .getMethod () .getParameterTypes () Try {Method m = classz.getMethod (method, parameterTypes); if (m! = null & & m.isAnnotationPresent (MyDataSource.class)) {MyDataSource data = m.getAnnotation (MyDataSource.class); logger.info ("method: {}, datasource: {}", m.getName (), data.value (). GetName ()) JdbcContextHolder.putDataSource (data.value (). GetName ()); / / put the data source in the current thread}} catch (Exception e) {logger.error ("get datasource error", e); / / choose master JdbcContextHolder.putDataSource (DataSourceType.Master.getName ()) by default / / data source in the current thread} @ AfterReturning ("aspect ()") public void after (JoinPoint point) {JdbcContextHolder.clearDataSource ();}} IV. Data source management class public class JdbcContextHolder {private final static ThreadLocal local = new ThreadLocal (); public static void putDataSource (String name) {local.set (name);} public static String getDataSource () {return local.get () } public static void clearDataSource () {local.remove ();} V. Data source annotations and enumerations
When we switch data sources, we usually do this before calling the method of a specific interface, so we define a method annotation. When AOP detects this comment on the method, we switch according to the name of the value in the note.
@ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.METHOD) public @ interface MyDataSource {DataSourceType value ();} public enum DataSourceType {/ / master table Master ("master"), / / slave table Slave ("slave"); private String name; private DataSourceType (String name) {this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name VI. Notes on tangent points
Since our dynamic data source is configured with a default library, annotations are not required if the method is to operate the default library. If we want to operate a non-default data source, we need to add @ MyDataSource ("data source name") annotation to the method, so that we can use AOP to dynamically switch.
Componentpublic class xxxServiceImpl {@ Resource private XxxMapperExt xxxMapperExt; @ MyDataSource (value= DataSourceType.Slave) public List getAll () {return xxxMapperExt.getAll ();}}
Original text link:
Http://tech.dianwoda.com/2018/03/28/spring-boot-aopfang-shi-shi-xian-duo-shu-ju-yuan-qie-huan/
At this point, I believe you have a deeper understanding of "spring-boot combined with AOP to achieve dynamic configuration of data sources". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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: 287
*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.