In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to achieve read-write separation based on JNDI in Java". In daily operation, I believe many people have doubts about how to achieve read-write separation in Java based on JNDI. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to achieve read-write separation in Java based on JNDI". Next, please follow the editor to study!
I. JNDI data source configuration
Under the conf directory of Tomcat, context.xml adds the following JNDI configuration to the label:
2. Use of JNDI data sources
1. In ordinary web projects
(1) add the following configuration to the web.xml file (or not):
DataSourceMaster javax.sql.DataSource Container dataSourceSlave javax.sql.DataSource Container III. Web.xml configuration Archetype Created Web Application log4jConfigLocation classpath:log4j.properties log4jRefreshInterval 60000 CharacterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding utf-8 forceEncoding true CharacterEncodingFilter xiyun xiyun org.springframework.web.servlet.DispatcherServlet contextConfigLocation Classpath:conf/spring/spring-servlet.xml 1 xiyun * .do IV. Spring-servlet.xml configuration 5. Spring-db.xml configuration Classpath:conf/sqlMap/*.xml VI. Log4j.properties configuration log4j.rootLogger=DEBUG CATALINA# Define all the appenderslog4j.appender.CATALINA=org.apache.log4j.RollingFileAppenderlog4j.appender.CATALINA.File=$ {catalina.base} / logs/catalina.loglog4j.appender.CATALINA.Append=truelog4j.appender.CATALINA.MaxFileSize=10MBlog4j.appender.CATALINA.Encoding=UTF-8# Roll-over the log once per daylog4j.appender.CATALINA.layout = org.apache.log4j.PatternLayoutlog4j.appender.CATALINA.layout.ConversionPattern =% d [% t]%-5p% c -% m% nlog4j.organizder.LOCALHOSTorganizorg.apache.log4j.RollingFileAppenderlog4j.accounder.LOCALHOST.Fileholders ${ Catalina.base} / logs/localhost.loglog4j.appender.LOCALHOST.MaxFileSize=10MBlog4j.appender.LOCALHOST.Append=truelog4j.appender.LOCALHOST.Encoding=UTF-8log4j.appender.LOCALHOST.layout = org.apache.log4j.PatternLayoutlog4j.appender.LOCALHOST.layout.ConversionPattern =% d [% t]%-5p% c -% m% nlog4j.organizder.MANAGERSecretorg.apache.log4j.RollingFileAppenderlog4j.accounder.MANAGER.FileFILERED ${catalina.base} / logs/manager.loglog4j.appender.MANAGER.MaxFileSize=10MBlog4j.appender.MANAGER.Append=truelog4j.appender.MANAGER.Encoding=UTF-8log4j.appender .MANAGER.DatePattern ='. 'yyyy-MM-dd'.log'log4j.appender.MANAGER.layout = org.apache.log4j.PatternLayoutlog4j.appender.MANAGER.layout.ConversionPattern =% d [% t]%-5p% c -% m% nlog4j.roomder.Hostel Managerciorg.apache.log4j.RollingFileAppenderlog4j.rolllingFileAppenderlog4j.roomder.HOSTUST MANAGER.Fileframes ${catalina.base} / logs/host-manager.loglog4j.appender.HOST-MANAGER.MaxFileSize=10MBlog4j.appender.HOST-MANAGER.Append=truelog4j.appender.HOST-MANAGER.Encoding=UTF-8log4j.appender. HOST-MANAGER.DatePattern='.'yyyy-MM-dd'.log'log4j.appender.HOST-MANAGER.layout = org.apache.log4j.PatternLayoutlog4j.appender.HOST-MANAGER.layout.ConversionPattern =% d [% t]%-5p% c -% m%nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.CONSOLE.Encoding=UTF-8log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayoutlog4j.appender.CONSOLE.layout.ConversionPattern =% d [% t]%-5p% c -% m % n # Configure which loggers log to which promoderslog4j.logger.org.apache.catalina.core.ContainerBase.[ Catalina] .localhost = INFO LOCALHOSTlog4j.logger.org.apache.catalina.core.ContainerBase.[ Catalina] .[ localhost] .[ / manager] = INFO, Managerlog4j.logger.org.apache.catalina.core.ContainerBase.[ Catalina] .[ localhost]. [/ host-manager] = INFO, HOST- Manager VII, related routing data source switching logic code package com.xiaoxi.config Import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import java.util.Map;public class DynamicRoutingDataSource extends AbstractRoutingDataSource {@ Override public void setTargetDataSources (Map targetDataSources) {super.setTargetDataSources (targetDataSources); super.afterPropertiesSet ();} @ Override protected Object determineCurrentLookupKey () {return DataSourceContextHolder.getDbType ();}} package com.xiaoxi.config;/** * thread context
* used to save the thread local variable DbType (for switching data sources) * if it is an asynchronous thread operation, you need to use InheritableThreadLocal (variables of the parent thread) * * @ see [related classes / methods] (optional) * @ since [product / module version] (optional) * / public class DataSourceContextHolder {private static final ThreadLocal contextHolder = new ThreadLocal (); public static ThreadLocal getLocal () {return contextHolder } private DataSourceContextHolder () {} public static String getDbType () {return contextHolder.get () = = null? DbType.MASTER.dbType: contextHolder.get (). DbType;} public static void setDbType (DbType dbType) {contextHolder.set (dbType);} public static void clearDbType () {contextHolder.remove ();} public enum DbType {MASTER ("Master"), SLAVE ("Slave"); private String dbType; DbType (String dbType) {this.dbType = dbType } public String getDbType () {return dbType;} package com.xiaoxi.aop;import com.xiaoxi.config.DataSourceContextHolder;import org.apache.log4j.Logger;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component / * data source section, which is used to switch between read and write data sources before executing sql
* < feature description > * * @ see [related classes / methods] (optional) * @ since [product / module version] (optional) * / @ Aspect@Order (- 1) @ Componentpublic class DataSourceAop {private static Logger logger = Logger.getLogger (DataSourceAop.class); @ Before ("execution (* com.xiaoxi.dao..*.query* (..)") Public void setReadDataSourceType () {DataSourceContextHolder.setDbType (DataSourceContextHolder.DbType.MASTER); logger.debug ("[DataSourceAop] DataSource Covert To SLAVE");} @ Before ("execution (* com.xiaoxi.dao..*.insert* (..)" + "| execution (* com.xiaoxi.dao..*.update* (..))" + "| | execution (* com.xiaoxi.dao..*.delete* (..)") Public void setWriteDataSourceType () {DataSourceContextHolder.setDbType (DataSourceContextHolder.DbType.SLAVE); logger.debug ("[DataSourceAop] DataSource Covert To MASTER");} / * * ☆ can also obtain the routing field in the parameters to switch the data source ☆ * * / @ Pointcut ("execution (* com.xiaoxi.dao..*.* (..)") Public void cutPoint () {} @ Before (value= "cutPoint ()") public void setDynamicDataSource (JoinPoint point) {String className = point.getTarget (). GetClass (). GetSimpleName (); String methodName = point.getSignature (). GetName (); String log = "[DataSourceAop] className:%s, methodName:%s"; logger.debug (String.format (log, className, methodName));}} VIII. Problems encountered in the construction process and solutions.
1. Failed to inject data sources dataSourceMaster and dataSourceSlave
The data source name of the jndiName configuration in spring is different from the Resource name in the Tomcat configuration file, which is not consistent, where java:comp/env is the environment, otherwise it will be reported to can not find jndi name.
2. Cannot create JDBC driver of class''for connect URL' null'
3. The requested resource is not available
Analysis of web.xml and servlet.xml found that the configuration is correct, annotation driver and package scan are configured, but still can not access, and later found that
There are problems with the log printed during the startup of the project, as follows:
2019-12-17 16 userInfo 20V 41767 [RMI TCP Connection (3)-127.0.0.1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping- Mapped "{[/ userInfo], methods= [GET]}" onto public java.lang.String com.xiaoxi.controller.UserInfoController.queryUserInfoById (java.lang.String)
Through the analysis, it is found that the request mapping here is mapped to the specific method through the requestMapping of controller, but the requestMapping path on the method is lost. It is found that the method RequestMapping is written as follows:
@ Controller@RequestMapping ("/ userInfo") public class UserInfoController {private static Logger logger = Logger.getLogger (UserInfoController.class); @ Autowired private UserInfoService userInfoService; @ ResponseBody @ RequestMapping (name= "/ queryUserInfoById", method = RequestMethod.GET) public String queryUserInfoById (@ RequestParam ("id") String id) {logger.info ("UserInfoController.queryUserInfoById. Id: {}" + id); UserInfo userInfo = userInfoService.queryUserInfoById (id); return JSON.toJSONString (userInfo);}}
The RequestMapping attribute name here should be changed to value, otherwise it will be resolved to empty (see the annotation definition)
At this point, the study on "how to achieve read-write separation in Java based on JNDI" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.