In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to achieve dynamic data source switching in AbstractRoutingDataSource AOP". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Database configuration: application.properties
# # datasource master # spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/master?characterEncoding=UTF-8&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=123456## datasource slave # spring.datasource-slave.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource-slave.driver-class-name=com.mysql.jdbc.Driverspring.datasource-slave.url=jdbc:mysql://localhost:3306/slave?characterEncoding=UTF-8&serverTimezone=UTCspring.datasource -slave.username=rootspring.datasource-slave.password=123456 writes database name annotations public interface Datasources {String MASTER_DB = "masterDB" String SLAVE_DB = "slaveDB";} configure data source @ Configurationpublic class DataSourceConfig {/ / destroy-method= "close" is to put the connection back into the datapool when the connection is not in use, so that it can be called next time. @ Bean (destroyMethod = "close", name = Datasources.MASTER_DB) @ ConfigurationProperties (prefix = "spring.datasource") public DataSource dataSource () {return DataSourceBuilder.create (). Type (DruidDataSource.class). Build ();} @ Bean (destroyMethod = "close", name = Datasources.SLAVE_DB) @ ConfigurationProperties (prefix = "spring.datasource-slave") public DataSource dataSourceSlave () {return DataSourceBuilder.create () .type (DruidDataSource.class). Build () }} configured as dynamic data source @ Configuration@MapperScan (basePackages = {"com.example.dao"}) public class MybatisConfig {@ Autowired @ Qualifier (Datasources.MASTER_DB) private DataSource masterDB; @ Autowired @ Qualifier (Datasources.SLAVE_DB) private DataSource slaveDB; / * dynamic data source * / @ Bean (name = "dynamicDataSource") public DataSource dynamicDataSource () {DynamicDataSource dynamicDataSource = new DynamicDataSource () / / default data source dynamicDataSource.setDefaultTargetDataSource (masterDB); / / configure multiple data sources Map dsMap = new HashMap (); dsMap.put (Datasources.MASTER_DB, masterDB); dsMap.put (Datasources.SLAVE_DB, slaveDB); dynamicDataSource.setTargetDataSources (dsMap); return dynamicDataSource } @ Bean @ ConfigurationProperties (prefix = "mybatis") public SqlSessionFactoryBean sqlSessionFactoryBean () {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean (); / / configure the data source here as the key configuration. If dynamicDataSource is not used as the data source, you cannot switch sqlSessionFactoryBean.setDataSource (dynamicDataSource ()); return sqlSessionFactoryBean. }} use ThreadLocal to securely manage the data source used by the current process to connect public class DataSourceContextHolder {/ * default data source * / public static final String DEFAULT_DATASOURCE = Datasources.MASTER_DB; private static final ThreadLocal contextHolder = new ThreadLocal (); / / set the data source name public static void setDB (String dbType) {System.out.println ("switch to {} data source:" + dbType) ContextHolder.set (dbType);} / / get the data source name public static String getDB () {return (contextHolder.get ());} / clear the data source name public static void clearDB () {contextHolder.remove () }} by writing facets, we intercept all the methods we customize to cut library annotations, and dynamically select the data source @ Aspect@Componentpublic class DynamicDataSourceAspect {@ Before ("@ annotation (com.example.util.RoutingDataSource)") public void beforeSwitchDS (JoinPoint joinPoint) {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature (); Method method = methodSignature.getMethod (); String dataSource = DataSourceContextHolder.DEFAULT_DATASOURCE If (method.isAnnotationPresent (RoutingDataSource.class)) {RoutingDataSource routingDataSource = method.getDeclaredAnnotation (RoutingDataSource.class); dataSource = routingDataSource.value ();} DataSourceContextHolder.setDB (dataSource);} @ After ("@ annotation (com.example.util.RoutingDataSource)") public void afterSwitchDS (JoinPoint point) {DataSourceContextHolder.clearDB () }} dynamically fetch the string public class DynamicDataSource extends AbstractRoutingDataSource {@ Override protected Object determineCurrentLookupKey () {System.out.println ("data source is {}:" + DataSourceContextHolder.getDB ()); return DataSourceContextHolder.getDB () }} cancel the automatic configuration of the data source and configure @ SpringBootApplication (exclude = {DataSourceAutoConfiguration.class}) public class CutDataBaseApplication {public static void main (String [] args) {SpringApplication.run (CutDataBaseApplication.class, args) using the data source defined here;}} use / * * @ author aYong * @ version 1.0 * @ date 2019-7-24 * / @ RestController@RequestMapping ("/ route") public class SysUserController {@ Autowired private SysUserService sysUserService @ GetMapping ("/ test1") public SysUser test1 (long id) {return sysUserService.test1 (id);} @ GetMapping ("/ test2") public Integer test2 (long id, String name) {return sysUserService.test2 (id, name);}} "how AbstractRoutingDataSource AOP implements dynamic data source switching" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.