這篇文章主要介紹,通過Spring Boot整合Mybatis后如何實現(xiàn)在一個工程中實現(xiàn)多數(shù)據(jù)源。同時可實現(xiàn)讀寫分離。
準備工作環(huán)境:
windows jdk 8 maven 3.0 IDEA創(chuàng)建數(shù)據(jù)庫表
在mysql中創(chuàng)建student庫并執(zhí)行下面查詢創(chuàng)建student表
-- ---------------------------- -- Table structure for student -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `sno` int(15) NOT NULL, `sname` varchar(50) DEFAULT NULL, `sex` char(2) DEFAULT NULL, `dept` varchar(25) DEFAULT NULL, `birth` date DEFAULT NULL, `age` int(3) DEFAULT NULL, PRIMARY KEY (`sno`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES ("1", "李同學", "1", "王同學學習成績很不錯", "2010-07-22", "17");
在mysql中創(chuàng)建teacher庫并執(zhí)行下面查詢創(chuàng)建teacher表
-- ---------------------------- -- Table structure for teacher -- ---------------------------- DROP TABLE IF EXISTS `teacher`; CREATE TABLE `teacher` ( `Tno` varchar(20) NOT NULL DEFAULT "", `Tname` varchar(50) DEFAULT NULL, `sex` char(2) DEFAULT NULL, `dept` varchar(25) DEFAULT NULL, `birth` date DEFAULT NULL, `age` int(3) DEFAULT NULL, PRIMARY KEY (`Tno`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of teacher -- ---------------------------- INSERT INTO `teacher` VALUES ("1", "王老師", "1", "王老師上課很認真", "2018-07-06", "35");構(gòu)建工程
4.0.0 cn.zhangbox spring-boot-study 1.0-SNAPSHOT cn.zhangbox spring-boot-mybatis-datasource 0.0.1-SNAPSHOT jar spring-boot-mybatis-datasource this project for Spring Boot UTF-8 UTF-8 1.8 3.4 1.10 1.2.0 1.16.14 1.2.41 1.1.2 aliyunmaven http://maven.aliyun.com/nexus/content/groups/public/ org.mybatis.spring.boot mybatis-spring-boot-starter ${mybatis-spring-boot.version} org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test org.apache.commons commons-lang3 ${commons-lang3.version} commons-codec commons-codec ${commons-codec.version} com.alibaba fastjson ${fastjson.version} com.alibaba druid-spring-boot-starter ${druid.version} org.projectlombok lombok ${lombok.version} spring-boot-mybatis-datasource org.apache.maven.plugins maven-compiler-plugin 3.5.1 1.8 UTF-8 org.apache.maven.plugins maven-surefire-plugin 2.19.1 org.springframework.boot spring-boot-maven-plugin org.springframework springloaded 1.2.4.RELEASE cn.zhangbox.admin.SpringBootDruidApplication -Dfile.encoding=UTF-8 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 true true org.springframework.boot spring-boot-maven-plugin cn.zhangbox.admin.SpringBootDruidApplication -Dfile.encoding=UTF-8 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 true true
注意:這里引入了lombok插件節(jié)省編寫實體類時候?qū)?b>get和set方法,這里在idea中進行set和get操作需要下載lombok插件,在設(shè)置頁面的plugins中搜索lombok插件在中央插件庫下載后重啟idea即可,更詳細的lombok使用教程可以查考:
程序員DD的lombok系列教程:Lombok:讓JAVA代碼更優(yōu)雅
修改YML配置#公共配置 server: port: 80 tomcat: uri-encoding: UTF-8 spring: #激活哪一個環(huán)境的配置文件 profiles: active: dev #連接池配置 datasource: #配置student庫驅(qū)動和連接池 student: driver-class-name: com.mysql.jdbc.Driver # 使用druid數(shù)據(jù)源 type: com.alibaba.druid.pool.DruidDataSource #配置teacher庫驅(qū)動和連接池 teacher: driver-class-name: com.mysql.jdbc.Driver # 使用druid數(shù)據(jù)源 type: com.alibaba.druid.pool.DruidDataSource druid: # 配置測試查詢語句 validationQuery: SELECT 1 FROM DUAL # 初始化大小,最小,最大 initialSize: 10 minIdle: 10 maxActive: 200 # 配置一個連接在池中最小生存的時間,單位是毫秒 minEvictableIdleTimeMillis: 180000 testOnBorrow: false testWhileIdle: true removeAbandoned: true removeAbandonedTimeout: 1800 logAbandoned: true # 打開PSCache,并且指定每個連接上PSCache的大小 poolPreparedStatements: true maxOpenPreparedStatements: 100 # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,"wall"用于防火墻 filters: stat,wall,log4j # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #mybatis mybatis: # 實體類掃描 type-aliases-package: cn.zhangbox.springboot.entity # 配置映射文件位置 mapper-locations: classpath:mapper/*.xml # 開啟駝峰匹配 mapUnderscoreToCamelCase: true --- #開發(fā)環(huán)境配置 server: #端口 port: 8080 spring: profiles: dev # 數(shù)據(jù)源配置 datasource: student: url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 teacher: url: jdbc:mysql://127.0.0.1:3306/teacher?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 #日志 logging: config: classpath:log/logback.xml path: log/spring-boot-mybatis-datasource --- #測試環(huán)境配置 server: #端口 port: 80 spring: profiles: test # 數(shù)據(jù)源配置 datasource: student: url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 teacher: url: jdbc:mysql://127.0.0.1:3306/teacher?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 #日志 logging: config: classpath:log/logback.xml path: /home/log/spring-boot-mybatis-datasource --- #生產(chǎn)環(huán)境配置 server: #端口 port: 8080 spring: profiles: prod # 數(shù)據(jù)源配置 datasource: student: url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 teacher: url: jdbc:mysql://127.0.0.1:3306/teacher?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 #日志 logging: config: classpath:log/logback.xml path: /home/log/spring-boot-mybatis-datasource
這里進行了mybatis整合,如果不會mybatis整合可以參考我寫的這篇文章:
SpringBoot非官方教程 | 第六篇:SpringBoot整合mybatis
在工程resources文件夾下新建文件夾log,并在該文件夾下創(chuàng)建logback.xml文件,加入以下配置:
${CONSOLE_LOG_PATTERN} UTF-8 info ${LOG_PATH}/log_debug.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${LOG_PATH}/debug/log-debug-%d{yyyy-MM-dd}.%i.log 500MB 30 debug ACCEPT DENY ${LOG_PATH}/log_info.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${LOG_PATH}/info/log-info-%d{yyyy-MM-dd}.%i.log 500MB 30 info ACCEPT DENY ${LOG_PATH}/log_warn.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${LOG_PATH}/warn/log-warn-%d{yyyy-MM-dd}.%i.log 500MB 30 warn ACCEPT DENY ${LOG_PATH}/log_error.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${LOG_PATH}/error/log-error-%d{yyyy-MM-dd}.%i.log 500MB 30 error ACCEPT DENY
注意::loback配置文件中
name的屬性值一定要是當前工程的java代碼的完整目錄,因為mybatis打印的日志級別是debug級別的,因此需要配置debug級別日志掃描的目錄。
創(chuàng)建Druid配置類在工程java代碼目錄下創(chuàng)建config的目錄在下面創(chuàng)建DruidDBConfig類加入以下代碼:
@Configuration public class DruidDBConfig { @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); //設(shè)置控制臺管理用戶 reg.addInitParameter("loginUsername","root"); reg.addInitParameter("loginPassword","root"); // 禁用HTML頁面上的“Reset All”功能 reg.addInitParameter("resetEnable","false"); //reg.addInitParameter("allow", "127.0.0.1"); //白名單 return reg; } @Bean public FilterRegistrationBean filterRegistrationBean() { //創(chuàng)建過濾器 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); MapinitParams = new HashMap (); //忽略過濾的形式 initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.setInitParameters(initParams); //設(shè)置過濾器過濾路徑 filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } }
注意:這里ServletRegistrationBean 配置bean中通過addInitParameter設(shè)置了管控臺的用戶名密碼都是root,可以在這里進行自定義配置也可以將這里的用戶名密碼通過轉(zhuǎn)移數(shù)據(jù)庫進行定制化配置實現(xiàn)。
創(chuàng)建Student數(shù)據(jù)源配置類在工程java代碼目錄下創(chuàng)建config的目錄在下面創(chuàng)建StudentDataSourceConfig類加入以下代碼:
@Configuration @MapperScan(basePackages ="cn.zhangbox.springboot.dao.student",sqlSessionFactoryRef = "studentSqlSessionFactory")//mybatis接口包掃描 public class StudentDataSourceConfig { @Value("${spring.datasource.student.type}") private Class extends DataSource> dataSourceType; /** *初始化連接池 * @return */ @Bean(name = "studentDataSource") @ConfigurationProperties(prefix = "spring.datasource.student") @Primary public DataSource writeDataSource() { return DataSourceBuilder.create().type(dataSourceType).build(); } /** * * 構(gòu)建 SqlSessionFactory * @return */ @Bean(name = "studentSqlSessionFactory") @Primary public SqlSessionFactory studentSqlSessionFactory(@Qualifier("studentDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //bean.setTypeAliasesPackage("com.ztzq.data.beans.bigdata"); bean.setVfs(SpringBootVFS.class); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/student/*.xml")); return bean.getObject(); } /** * 配置事物 * @param dataSource * @return */ @Bean(name = "studentTransactionManager") @Primary public DataSourceTransactionManager TransactionManager(@Qualifier("studentDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } /** * 構(gòu)建 SqlSessionTemplate * @param sqlSessionFactory * @return * @throws Exception */ @Bean(name = "studentSqlSessionTemplate") @Primary public SqlSessionTemplate SqlSessionTemplate(@Qualifier("studentSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }創(chuàng)建Teacher數(shù)據(jù)源配置類
在工程java代碼目錄下創(chuàng)建config的目錄在下面創(chuàng)建TeacherDataSourceConfig類加入以下代碼:
@Configuration @MapperScan(basePackages ="cn.zhangbox.springboot.dao.teacher",sqlSessionFactoryRef = "teacherSqlSessionFactory")//mybatis接口包掃描 public class TecaherDataSourceConfig { @Value("${spring.datasource.teacher.type}") private Class extends DataSource> dataSourceType; /** *初始化連接池 * @return */ @Bean(name = "teacherDataSource") @ConfigurationProperties(prefix = "spring.datasource.teacher") public DataSource writeDataSource() { return DataSourceBuilder.create().type(dataSourceType).build(); } /** * * 構(gòu)建 SqlSessionFactory * @return */ @Bean(name = "teacherSqlSessionFactory") public SqlSessionFactory teacherSqlSessionFactory(@Qualifier("teacherDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //bean.setTypeAliasesPackage("com.ztzq.data.beans.bigdata"); bean.setVfs(SpringBootVFS.class); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/teacher/*.xml")); return bean.getObject(); } /** * 配置事物 * @param dataSource * @return */ @Bean(name = "teacherTransactionManager") public DataSourceTransactionManager TransactionManager(@Qualifier("teacherDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } /** * 構(gòu)建 SqlSessionTemplate * @param sqlSessionFactory * @return * @throws Exception */ @Bean(name = "teacherSqlSessionTemplate") public SqlSessionTemplate SqlSessionTemplate(@Qualifier("teacherSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }創(chuàng)建實體
在工程java代碼目錄下創(chuàng)建entity的目錄在下面創(chuàng)建Student類加入以下代碼:
@Data @EqualsAndHashCode(callSuper = false) public class Student { private static final long serialVersionUID = 1L; /** * 主鍵id */ private Integer sno; /** * 學生姓名 */ private String sname; /** * 性別 */ private String sex; /** * 生日 */ private String birth; /** * 年齡 */ private String age; /** * 簡介 */ private String dept; }
在工程java代碼目錄下創(chuàng)建entity的目錄在下面創(chuàng)建Teacher類加入以下代碼:
@Data @EqualsAndHashCode(callSuper = false) public class Teacher { private static final long serialVersionUID = 1L; /** * 主鍵id */ private Integer tno; /** * 老師姓名 */ private String tname; /** * 性別 */ private String sex; /** * 生日 */ private String birth; /** * 年齡 */ private String age; /** * 簡介 */ private String dept; }創(chuàng)建Controller
在工程java代碼目錄下創(chuàng)建controller的目錄在下面創(chuàng)建StudentConteroller類加入以下代碼:
@Controller @RequestMapping("/student") public class StudentConteroller { private static final Logger LOGGER = LoggerFactory.getLogger(StudentConteroller.class); @Autowired protected StudentService studentService; /** * 查詢所有的學生信息 * * @param sname * @param age * @param modelMap * @return */ @ResponseBody @GetMapping("/list") public String list(String sname, Integer age, ModelMap modelMap) { String json = null; try { ListstudentList = studentService.getStudentList(sname, age); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢成功"); modelMap.put("studentList", studentList); json = JSON.toJSONString(modelMap); } catch (Exception e) { e.printStackTrace(); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢失敗===>" + e); LOGGER.error("查詢失敗===>" + e); json = JSON.toJSONString(modelMap); } return json; } }
在工程java代碼目錄下創(chuàng)建controller的目錄在下面創(chuàng)建TeacherConteroller類加入以下代碼:
@Controller @RequestMapping("/teacher") public class TeacherConteroller { private static final Logger LOGGER = LoggerFactory.getLogger(TeacherConteroller.class); @Autowired protected TeacherService teacherService; /** * 查詢所有的老師信息 * * @param tname * @param age * @param modelMap * @return */ @ResponseBody @GetMapping("/list") public String list(String tname, Integer age, ModelMap modelMap) { String json = null; try { List創(chuàng)建ServiceteacherList = teacherService.getTeacherList(tname, age); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢成功"); modelMap.put("teacherList", teacherList); json = JSON.toJSONString(modelMap); } catch (Exception e) { e.printStackTrace(); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢失敗===>" + e); LOGGER.error("查詢失敗===>" + e); json = JSON.toJSONString(modelMap); } return json; } }
在工程java代碼目錄下面創(chuàng)建service目錄在下面創(chuàng)建StudentService類加入以下代碼:
public interface StudentService { /** * 查詢所有的學生信息 * * @param sname * @param age * @return */ ListgetStudentList(String sname, Integer age); }
在工程java代碼目錄下面創(chuàng)建service目錄在下面創(chuàng)建TeacherService類加入以下代碼:
public interface TeacherService { /** * 查詢所有的老師信息 * * @param tname * @param age * @return */ List創(chuàng)建ServiceImplgetTeacherList(String tname, Integer age); }
在工程java代碼目錄下的service的目錄下面創(chuàng)建impl目錄在下面創(chuàng)建StudentServiceImpl類加入以下代碼:
@Service("StudentService") @Transactional(readOnly = true, rollbackFor = Exception.class) public class StudentServiceImpl implements StudentService { @Autowired StudentDao studentDao; @Override public ListgetStudentList(String sname, Integer age) { return studentDao.getStudentList(sname,age); } }
在工程java代碼目錄下的service的目錄下面創(chuàng)建impl目錄在下面創(chuàng)建TeacherServiceImpl類加入以下代碼:
@Service("TeacherService") @Transactional(readOnly = true, rollbackFor = Exception.class) public class TeacherServiceImpl implements TeacherService { @Autowired TeacherDao teacherDao; @Override public List創(chuàng)建DaogetTeacherList(String tname, Integer age) { return teacherDao.getTeacherList(tname,age); } }
在工程java代碼目錄下創(chuàng)建dao的目錄下面創(chuàng)建student目錄在此目錄下創(chuàng)建StudentDao類加入以下代碼:
public interface StudentDao { ListgetStudentList(@Param("sname")String sname, @Param("age")Integer age); }
在工程java代碼目錄下創(chuàng)建dao的目錄下面創(chuàng)建teacher目錄在此目錄下創(chuàng)建TeacherDao類加入以下代碼:
public interface TeacherDao { List創(chuàng)建Mapper映射文件getTeacherList(@Param("tname") String tname, @Param("age") Integer age); }
在工程resource目錄下創(chuàng)建mapper的目錄下創(chuàng)建student目錄在此目錄下面創(chuàng)建StudentMapper.xml映射文件加入以下代碼:
在工程resource目錄下創(chuàng)建mapper的目錄下創(chuàng)建teacher目錄在此目錄下面創(chuàng)建TeacherMapper.xml映射文件加入以下代碼:
創(chuàng)建啟動類
@SpringBootApplication public class SpringBootManyDataSourceApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringBootManyDataSourceApplication.class, args); } }啟動項目進行測試: 控制臺打印
. ____ _ __ _ _ / / ___"_ __ _ _(_)_ __ __ _ ( ( )\___ | "_ | "_| | "_ / _` | / ___)| |_)| | | | | || (_| | ) ) ) ) " |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.3.RELEASE) 2018-07-09 19:58:22.757 INFO 10096 --- [ main] .z.s.SpringBootManyDataSourceApplication : Starting SpringBootManyDataSourceApplication on 99IHXFJDHAQ7H7N with PID 10096 (started by Administrator in D:開源項目spring-boot-study) 2018-07-09 19:58:22.780 INFO 10096 --- [ main] .z.s.SpringBootManyDataSourceApplication : The following profiles are active: dev 2018-07-09 19:58:22.987 INFO 10096 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@35e5d0e5: startup date [Mon Jul 09 19:58:22 CST 2018]; root of context hierarchy 2018-07-09 19:58:23.460 INFO 10096 --- [kground-preinit] o.h.validator.internal.util.Version : HV000001: Hibernate Validator 5.3.5.Final 2018-07-09 19:58:24.220 INFO 10096 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean "filterRegistrationBean" with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=druidDBConfig; factoryMethodName=filterRegistrationBean; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [cn/zhangbox/springboot/config/DruidDBConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.alibaba.druid.spring.boot.autoconfigure.stat.DruidWebStatFilterConfiguration; factoryMethodName=filterRegistrationBean; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/stat/DruidWebStatFilterConfiguration.class]] 2018-07-09 19:58:25.440 INFO 10096 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2018-07-09 19:58:25.457 INFO 10096 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2018-07-09 19:58:25.459 INFO 10096 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14 2018-07-09 19:58:25.594 INFO 10096 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-07-09 19:58:25.594 INFO 10096 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2608 ms 2018-07-09 19:58:26.138 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: "statViewServlet" to [/druid/*] 2018-07-09 19:58:26.139 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: "dispatcherServlet" to [/] 2018-07-09 19:58:26.140 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: "statViewServlet" to [/druid/*] 2018-07-09 19:58:26.141 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet statViewServlet was not registered (possibly already registered?) 2018-07-09 19:58:26.146 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: "characterEncodingFilter" to: [/*] 2018-07-09 19:58:26.147 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: "hiddenHttpMethodFilter" to: [/*] 2018-07-09 19:58:26.148 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: "httpPutFormContentFilter" to: [/*] 2018-07-09 19:58:26.148 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: "requestContextFilter" to: [/*] 2018-07-09 19:58:26.149 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: "webStatFilter" to urls: [/*] 2018-07-09 19:58:27.694 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@35e5d0e5: startup date [Mon Jul 09 19:58:22 CST 2018]; root of context hierarchy 2018-07-09 19:58:27.792 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/student/list],methods=[GET]}" onto public java.lang.String cn.zhangbox.springboot.controller.StudentConteroller.list(java.lang.String,java.lang.Integer,org.springframework.ui.ModelMap) 2018-07-09 19:58:27.794 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/teacher/list],methods=[GET]}" onto public java.lang.String cn.zhangbox.springboot.controller.TeacherConteroller.list(java.lang.String,java.lang.Integer,org.springframework.ui.ModelMap) 2018-07-09 19:58:27.796 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity瀏覽器請求測試> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2018-07-09 19:58:27.796 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2018-07-09 19:58:27.837 INFO 10096 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-07-09 19:58:27.837 INFO 10096 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-07-09 19:58:27.893 INFO 10096 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-07-09 19:58:28.836 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-07-09 19:58:28.837 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name "studentDataSource" has been autodetected for JMX exposure 2018-07-09 19:58:28.838 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name "teacherDataSource" has been autodetected for JMX exposure 2018-07-09 19:58:28.838 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name "statFilter" has been autodetected for JMX exposure 2018-07-09 19:58:28.846 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean "studentDataSource": registering with JMX server as MBean [com.alibaba.druid.pool:name=studentDataSource,type=DruidDataSource] 2018-07-09 19:58:28.849 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean "teacherDataSource": registering with JMX server as MBean [com.alibaba.druid.pool:name=teacherDataSource,type=DruidDataSource] 2018-07-09 19:58:28.851 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean "statFilter": registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter] 2018-07-09 19:58:28.877 INFO 10096 --- [ main] o.a.coyote.http11.Http11NioProtocol : Initializing ProtocolHandler ["http-nio-8080"] 2018-07-09 19:58:28.905 INFO 10096 --- [ main] o.a.coyote.http11.Http11NioProtocol : Starting ProtocolHandler ["http-nio-8080"] 2018-07-09 19:58:28.930 INFO 10096 --- [ main] o.a.tomcat.util.net.NioSelectorPool : Using a shared selector for servlet write/read 2018-07-09 19:58:28.965 INFO 10096 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2018-07-09 19:58:28.972 INFO 10096 --- [ main] .z.s.SpringBootManyDataSourceApplication : Started SpringBootManyDataSourceApplication in 8.519 seconds (JVM running for 12.384) 2018-07-09 19:58:37.626 INFO 10096 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet "dispatcherServlet" 2018-07-09 19:58:37.626 INFO 10096 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet "dispatcherServlet": initialization started 2018-07-09 19:58:37.660 INFO 10096 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet "dispatcherServlet": initialization completed in 33 ms 2018-07-09 19:58:37.981 INFO 10096 --- [nio-8080-exec-1] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited 2018-07-09 19:58:41.381 INFO 10096 --- [nio-8080-exec-2] com.alibaba.druid.pool.DruidDataSource : {dataSource-2} inited
2018-07-09 19:58:22.779 [main] DEBUG c.z.springboot.SpringBootManyDataSourceApplication - Running with Spring Boot v1.5.3.RELEASE, Spring v4.3.8.RELEASE 2018-07-09 19:58:38.386 [http-nio-8080-exec-1] DEBUG c.z.s.dao.student.StudentDao.getStudentList - ==> Preparing: SELECT s.sno, s.sname, s.sex, s.dept, s.birth, s.age FROM student s WHERE 1 = 1 2018-07-09 19:58:38.409 [http-nio-8080-exec-1] DEBUG c.z.s.dao.student.StudentDao.getStudentList - ==> Parameters: 2018-07-09 19:58:38.436 [http-nio-8080-exec-1] DEBUG c.z.s.dao.student.StudentDao.getStudentList - <== Total: 2 2018-07-09 19:58:41.461 [http-nio-8080-exec-2] DEBUG c.z.s.dao.teacher.TeacherDao.getTeacherList - ==> Preparing: SELECT s.tno, s.tname, s.sex, s.dept, s.birth, s.age FROM teacher s WHERE 1 = 1 2018-07-09 19:58:41.462 [http-nio-8080-exec-2] DEBUG c.z.s.dao.teacher.TeacherDao.getTeacherList - ==> Parameters: 2018-07-09 19:58:41.472 [http-nio-8080-exec-2] DEBUG c.z.s.dao.teacher.TeacherDao.getTeacherList - <== Total: 1
這里使用logback配置中將不同級別的日志設(shè)置了在不同文件中打印,這樣很大程度上方便項目出問題查找問題。
Druid管控臺
druid鏈接池不知道怎么配置可以參考我寫的這篇文章:
SpringBoot進階教程 | 第三篇:整合Druid連接池以及Druid監(jiān)控
Spring Boot整合Mybatis實現(xiàn)多數(shù)據(jù)源源碼
歡迎關(guān)注我的微信公眾號獲取更多更全的學習資源,視頻資料,技術(shù)干貨!
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/71553.html
摘要:前言由于寫的文章已經(jīng)是有點多了,為了自己和大家的檢索方便,于是我就做了這么一個博客導航。 前言 由于寫的文章已經(jīng)是有點多了,為了自己和大家的檢索方便,于是我就做了這么一個博客導航。 由于更新比較頻繁,因此隔一段時間才會更新目錄導航哦~想要獲取最新原創(chuàng)的技術(shù)文章歡迎關(guān)注我的公眾號:Java3y Java3y文章目錄導航 Java基礎(chǔ) 泛型就這么簡單 注解就這么簡單 Druid數(shù)據(jù)庫連接池...
摘要:下一篇介紹基于的服務(wù)注冊與調(diào)用。服務(wù)提供者工程配置這里服務(wù)提供者是使用之前進階教程第三篇整合連接池以及監(jiān)控改造而來,這里一樣的部分就不再重復說明,下面將說明新增的部分。 Spring Cloud簡介 Spring Cloud是一個基于Spring Boot實現(xiàn)的云應(yīng)用開發(fā)工具,它為基于JVM的云應(yīng)用開發(fā)中涉及的配置管理、服務(wù)發(fā)現(xiàn)、斷路器、智能路由、微代理、控制總線、全局鎖、決策競選、分...
閱讀 3267·2021-11-18 10:02
閱讀 3443·2021-10-11 10:58
閱讀 3376·2021-09-24 09:47
閱讀 1120·2021-09-22 15:21
閱讀 3915·2021-09-10 11:10
閱讀 3277·2021-09-03 10:28
閱讀 1749·2019-08-30 15:45
閱讀 2136·2019-08-30 14:22