Springboot Druid +mybatis 多数据源监控,只能监控到主库SQL,从库不行 10C

配置如下
spring:
circle-datasource: #从库
#123.207.23.166:3306
name: db
url: jdbc:mysql://119.29.208.67:3307/ws?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
username: root
password: *****
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
minIdle: 5
maxActive: 100
initialSize: 10
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 50
removeAbandoned: true

spring:
datasource: #主库
#123.207.23.166:3306
name: db
url: jdbc:mysql://119.29.208.67:3306/ws?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
username: momo
password: *****
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
minIdle: 5
maxActive: 100
initialSize: 10
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 50
removeAbandoned: true
filters: stat
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
useGlobalDataSourceStat: true # 合并多个DruidDataSource的监控数据
druidLoginName: momo # 登录druid的账号
druidPassword: momo # 登录druid的密码

----------------------------------------------
   @Bean(name="circleDataSource",destroyMethod = "close", initMethod="init")
public DataSource dataSource(){
    DruidDataSource datasource =  new DruidDataSource();
    try {  
        datasource.setUrl(this.url);
       datasource.setDbType(type);
        datasource.setUsername(username);  
        datasource.setPassword(password);  
        datasource.setDriverClassName(driverClassName);  
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnBorrow);  
        datasource.setTestOnReturn(testOnReturn);  
        datasource.setPoolPreparedStatements(poolPreparedStatements);  
        datasource.setFilters(filters);
        datasource.setUseGlobalDataSourceStat(true);
    } catch (Exception e) {
        logger.error("druid configuration initialization filter", e);  
    }  
    return datasource;  
}

    ---------------------主库-------
      @Bean(name="dataSource",destroyMethod = "close", initMethod="init")
@Primary //不要漏了这
public DataSource dataSource(){
    DruidDataSource datasource = new DruidDataSource();
    try {  
        datasource.setUrl(this.dbUrl);  
        datasource.setDbType(dbType);
        datasource.setUsername(username);  
        datasource.setPassword(password);  
        datasource.setDriverClassName(driverClassName);  
        datasource.setInitialSize(initialSize);  
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnBorrow);  
        datasource.setTestOnReturn(testOnReturn);  
        datasource.setPoolPreparedStatements(poolPreparedStatements);  
        datasource.setFilters(filters);
        datasource.setUseGlobalDataSourceStat(true);
    } catch (SQLException e) {  
        logger.error("druid configuration initialization filter", e);  
    }  
    return datasource;  
}
/////////  下面是druid 监控访问的设置  /////////////////  
@Bean  
public ServletRegistrationBean druidServlet() {  
    ServletRegistrationBean reg = new ServletRegistrationBean();  
    reg.setServlet(new StatViewServlet());  
    reg.addUrlMappings("/druid/*");  //url 匹配  
  //  reg.addInitParameter("allow", "192.168.16.110,127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问)  
  //  reg.addInitParameter("deny", "192.168.16.111"); //IP黑名单 (存在共同时,deny优先于allow)  
    reg.addInitParameter("loginUsername", this.druidLoginName);//登录名  
    reg.addInitParameter("loginPassword", this.druidPassword);//登录密码  
    reg.addInitParameter("resetEnable", "false"); // 禁用HTML页面上的“Reset All”功能  
    return reg;  
}  

@Bean(name="druidWebStatFilter")  
public FilterRegistrationBean filterRegistrationBean() {  
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();  
    filterRegistrationBean.setFilter(new WebStatFilter());  
    filterRegistrationBean.addUrlPatterns("/*");  
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); //忽略资源  
    filterRegistrationBean.addInitParameter("profileEnable", "true");  
    filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");  
    filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");  
    return filterRegistrationBean;  
}

    ----------------------------------------------------
    ![图片说明](https://img-ask.csdn.net/upload/201807/21/1532162386_693657.png)
    从库在数据源是监控了,但是sql没有
    ![图片说明](https://img-ask.csdn.net/upload/201807/21/1532162432_671619.png)

4个回答

图片说明

图片说明

原来是从库yml配置漏了
filters: stat

我的两个数据源都配置了,但是两个库同事调用sql时,sql监控就清空了,只有单独一个数据源时可以监控,不知道为什么。
yml配置没有生效,只能在代码里set拦截器

public DataSource dbOneDataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setFilters("stat,wall,slf4j");
        return druidDataSource;
    }
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Springboot Druid +mybatis 多数据源监控,只能监控到主库SQL,从库不行
配置如下 spring: circle-datasource: #从库 #123.207.23.166:3306 name: db url: jdbc:mysql://119.29.208.67:3307/ws?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true username: root password: ***** driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource minIdle: 5 maxActive: 100 initialSize: 10 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 50 removeAbandoned: true spring: datasource: #主库 #123.207.23.166:3306 name: db url: jdbc:mysql://119.29.208.67:3306/ws?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true username: momo password: ***** driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource minIdle: 5 maxActive: 100 initialSize: 10 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 50 removeAbandoned: true filters: stat connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 useGlobalDataSourceStat: true # 合并多个DruidDataSource的监控数据 druidLoginName: momo # 登录druid的账号 druidPassword: momo # 登录druid的密码 ---------------------------------------------- @Bean(name="circleDataSource",destroyMethod = "close", initMethod="init") public DataSource dataSource(){ DruidDataSource datasource = new DruidDataSource(); try { datasource.setUrl(this.url); datasource.setDbType(type); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setFilters(filters); datasource.setUseGlobalDataSourceStat(true); } catch (Exception e) { logger.error("druid configuration initialization filter", e); } return datasource; } ---------------------主库------- @Bean(name="dataSource",destroyMethod = "close", initMethod="init") @Primary //不要漏了这 public DataSource dataSource(){ DruidDataSource datasource = new DruidDataSource(); try { datasource.setUrl(this.dbUrl); datasource.setDbType(dbType); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setFilters(filters); datasource.setUseGlobalDataSourceStat(true); } catch (SQLException e) { logger.error("druid configuration initialization filter", e); } return datasource; } ///////// 下面是druid 监控访问的设置 ///////////////// @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); //url 匹配 // reg.addInitParameter("allow", "192.168.16.110,127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问) // reg.addInitParameter("deny", "192.168.16.111"); //IP黑名单 (存在共同时,deny优先于allow) reg.addInitParameter("loginUsername", this.druidLoginName);//登录名 reg.addInitParameter("loginPassword", this.druidPassword);//登录密码 reg.addInitParameter("resetEnable", "false"); // 禁用HTML页面上的“Reset All”功能 return reg; } @Bean(name="druidWebStatFilter") public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); //忽略资源 filterRegistrationBean.addInitParameter("profileEnable", "true"); filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE"); filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION"); return filterRegistrationBean; } ---------------------------------------------------- ![图片说明](https://img-ask.csdn.net/upload/201807/21/1532162386_693657.png) 从库在数据源是监控了,但是sql没有 ![图片说明](https://img-ask.csdn.net/upload/201807/21/1532162432_671619.png)
为什么springboot+mybatis+mysql 数据库驱动无法加载?
#数据库配置 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.max-active=20 spring.datasource.max-idle=8 spring.datasource.min-idle=8 spring.datasource.initial-size=10 pom.xml配置依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>src\main\resources\templates\mybatisgenerator_config.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> 启动代码 package com.example.bookstore_demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication @MapperScan(basePackages = "com.example.bookstore_demo.dao") public class BookstoreDemoApplication { public static void main(String[] args) { SpringApplication.run(BookstoreDemoApplication.class, args); } } 报错Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2017-11-13 13:52:17.858 ERROR 4136 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Cannot determine embedded database driver class for database type NONE Action: If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active). Disconnected from the target VM, address: '127.0.0.1:49367', transport: 'socket' Process finished with exit code 0
springboot 整合mybatis 报错提示包扫描不进去
![图片说明](https://img-ask.csdn.net/upload/201908/14/1565777159_224084.png) ``` package com.liupeng; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication() @MapperScan(basePackages = "com.liupeng.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } } ``` ``` package com.liupeng.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.liupeng.mapper.UserMapper; import com.liupeng.pojo.User; @Service(value = "Userservice") public class UserServiceImpl implements Userservice { @Autowired private UserMapper userMapper; @Override public User getNamePassword(User user) { // TODO Auto-generated method stub return userMapper.selectgetNamePassword(user); } @Override public void saveUser(User user) { // TODO Auto-generated method stub } } ``` mapper.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.liupeng.mapper.UserMapper"> ``` ``` #------------------配置虚拟文件路径--start------------------------------ spring.http.multipart.location=E:\Java\java代码\Chaoyang\src\main\resources #-----------------------------------------数据库--start---------------------- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Drive spring.datasource.url=jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=GMT spring.datasource.username=root spring.datasource.password=liupeng.123 spring.datasource.druid.stat-view-servlet.allow=true #获取连接等待超时时间 spring.datasource.dbcp2.max-wait-millis=60000 #mybatis配置 mybatis.type-aliases-package=com.liupeng.pojo mybatis.mapper-locations=classpath:mapper/*.xml #通用Mapper配置 #mapper.mappers=com.liupeng.utils.MyMapper #mapper.not-empty=false #mapper.identity=MYSQL #分页插件配置 pagehelper.helperDialect=mysq1 pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql #文件上传配置 spring.http.multipart.maxFileSize=100Mb spring.http.multipart.maxRequestSize=1000Mb #配置api端口号 server.port=8080 #tomcat的URI编码 server.tomcat.uri-encoding=UTF-8 ``` ``` ERROR [main] - Application startup failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'registLoginController': Unsatisfied dependency expressed through field 'userservice'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Userservice': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [E:\Java\java代码\Chaoyang\target\classes\com\liupeng\mapper\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [tk/mybatis/mapper/autoconfigure/MapperAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\Java\java代码\Chaoyang\target\classes\mapper\UserMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:364) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1268) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:123) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:666) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:353) at org.springframework.boot.SpringApplication.run(SpringApplication.java:300) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1082) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1071) at com.liupeng.Application.main(Application.java:13) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Userservice': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [E:\Java\java代码\Chaoyang\target\classes\com\liupeng\mapper\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [tk/mybatis/mapper/autoconfigure/MapperAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\Java\java代码\Chaoyang\target\classes\mapper\UserMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:364) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1268) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:211) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583) ... 19 more Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [E:\Java\java代码\Chaoyang\target\classes\com\liupeng\mapper\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [tk/mybatis/mapper/autoconfigure/MapperAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\Java\java代码\Chaoyang\target\classes\mapper\UserMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1361) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1253) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:211) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583) ... 32 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [tk/mybatis/mapper/autoconfigure/MapperAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\Java\java代码\Chaoyang\target\classes\mapper\UserMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1177) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1072) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:211) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1346) ... 43 more Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\Java\java代码\Chaoyang\target\classes\mapper\UserMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ... 55 more Caused by: org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\Java\java代码\Chaoyang\target\classes\mapper\UserMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:523) at org.mybatis.spring.SqlSessionFactoryBean.afterPropertiesSet(SqlSessionFactoryBean.java:380) at org.mybatis.spring.SqlSessionFactoryBean.getObject(SqlSessionFactoryBean.java:547) at tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration.sqlSessionFactory(MapperAutoConfiguration.java:155) at tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration$$EnhancerBySpringCGLIB$$90d064bb.CGLIB$sqlSessionFactory$1(<generated>) at tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration$$EnhancerBySpringCGLIB$$90d064bb$$FastClassBySpringCGLIB$$b0514ca6.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) at tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration$$EnhancerBySpringCGLIB$$90d064bb.sqlSessionFactory(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ... 56 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:120) at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:92) at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:521) ... 69 more Caused by: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.liupeng.mapper.UserMapper.BaseResultMap at org.apache.ibatis.session.Configuration$StrictMap.put(Configuration.java:872) at org.apache.ibatis.session.Configuration$StrictMap.put(Configuration.java:844) at org.apache.ibatis.session.Configuration.addResultMap(Configuration.java:626) at org.apache.ibatis.builder.MapperBuilderAssistant.addResultMap(MapperBuilderAssistant.java:214) at org.apache.ibatis.builder.ResultMapResolver.resolve(ResultMapResolver.java:47) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:285) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:252) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElements(XMLMapperBuilder.java:244) at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:116) ... 71 more ```
springboot gradle mybatis MapperScan.factoryBean()异常
异常 ``` Caused by: java.lang.annotation.AnnotationFormatError: Invalid default: public abstract java.lang.Class org.mybatis.spring.annotation.MapperScan.factoryBean() at java.lang.reflect.Method.getDefaultValue(Method.java:612) ~[na:1.8.0_131] at org.springframework.core.annotation.AnnotationUtils.registerDefaultValues(AnnotationUtils.java:1258) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE] ``` 配置: ``` @Configuration @MapperScan(basePackages = EntMasterDataSourceConfig.BASE_PACKAGE, sqlSessionFactoryRef = "entMasterSqlSessionFactory") public class EntMasterDataSourceConfig { static final String BASE_PACKAGE = "com.sunlands.entmaster"; static final String MAPPER_LOCATION = "classpath:/*.xml"; @Value("${spring.datasource.ent_master.url}") private String dbUrl; @Value("${spring.datasource.ent_master.username}") private String dbUser; @Value("${spring.datasource.ent_master.password}") private String dbPassword; @Value("${spring.datasource.driver-class-name}") private String dbDriver; /** * 配置数据数据源 master * * @return */ @Bean(name = "entMasterDatasource") @Primary public DataSource masterDatasource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(dbDriver); dataSource.setUrl(dbUrl); dataSource.setUsername(dbUser); dataSource.setPassword(dbPassword); //连接池启动时创建的初始化连接数量 dataSource.setInitialSize(1); //连接池中可同时连接的最大的连接数 dataSource.setMaxActive(100); //连接池中最小的空闲的连接数,低于这个数量会被创建新的连接 dataSource.setMinIdle(5); //最大等待时间,当没有可用连接时,连接池等待连接释放的最大时间,超过该时间限制会抛出异常,如果设置-1表示无限等待 dataSource.setMaxWait(60000); //超过removeAbandonedTimeout时间后,是否进 行没用连接(废弃)的回收(默认为false,调整为true) dataSource.setRemoveAbandoned(true); //超过时间限制,回收没有用(废弃)的连接(默认为 300秒,调整为180) dataSource.setRemoveAbandonedTimeout(180); //默认提交 dataSource.setDefaultAutoCommit(true); //打开检查,用异步线程evict进行检查 dataSource.setTestWhileIdle(true); //就是在进行borrowObject进行处理时,对拿到的connection进行validateObject校验 dataSource.setTestOnBorrow(false); //就是在进行returnObject对返回的connection进行validateObject校验,个人觉得对数据库连接池的管理意义不大 dataSource.setTestOnReturn(false); // 代表检查的sql dataSource.setValidationQuery("select 1 from dual"); //代表在执行检查时,通过statement设置,statement.setQueryTimeout(validationQueryTimeout) dataSource.setValidationQueryTimeout(1); dataSource.setTimeBetweenEvictionRunsMillis(30000); return dataSource; } /** * 配置session工厂 * * @param entMasterDatasource * @return * @throws Exception */ @Bean(name = "entMasterSqlSessionFactory") @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier("entMasterDatasource") DataSource entMasterDatasource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(entMasterDatasource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(EntMasterDataSourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); } /** * 配置事务管理器 * * @param dataSource * @return */ @Bean(name = "entMasterTransactionManger") @Primary public DataSourceTransactionManager masterTransactionManger(@Qualifier("entMasterDatasource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } ``` gradle springboot是2.1.0 ``` dependencies { implementation('org.springframework.boot:spring-boot-starter-web') providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') testImplementation('org.springframework.boot:spring-boot-starter-test') compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.1.0.RELEASE' compile group: 'com.alibaba', name: 'fastjson', version: '1.2.51' compile group: 'com.alibaba', name: 'druid', version: '1.1.12' compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.1.0.RELEASE' compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1' compile group: 'mysql', name: 'mysql-connector-java', version:'5.1.34' compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2' compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.2' compile group: 'org.springframework', name: 'spring-jdbc', version: '5.1.2.RELEASE' compile group: 'org.springframework', name: 'spring-orm', version: '5.1.2.RELEASE' compile group: 'org.mybatis', name: 'mybatis', version: '3.4.6' } ```
springboot配置完druid,spring监控没有数据?
![图片说明](https://img-ask.csdn.net/upload/201908/10/1565422211_555424.png) 配置完之后,sql监控有数据,spring监控没有有数据,啥情况? ![图片说明](https://img-ask.csdn.net/upload/201908/10/1565422357_288228.png) ``` @Configuration public class DruidConfig { /** * 配置Druid监控 * 后台管理Servlet * @return */ @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","admin"); //默认就是允许所有访问 initParams.put("allow",""); //黑名单的IP initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } /** * 配置web监控的filter * @return */ @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","/static/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } } ```
关于SpringBoot+myBatis实体的字段返回前端后格式变化的问题
我的架构是 springBoot(1.5.9)+myBatis ,连接池用的是阿里的druid,以下是配置信息: 启动类: import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.github.pagehelper.PageHelper; /** * * @author wangxufei * */ @SpringBootApplication @EnableAutoConfiguration @MapperScan("com.mofangge.mapper") public class MfgAgencyApplication { @Value("${spring.datasource.username}") private String userName; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.url}") private String url; @Bean public ServletRegistrationBean druidServletRegistrationBean() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); servletRegistrationBean.setServlet(new StatViewServlet()); servletRegistrationBean.addUrlMappings("/druid/*"); return servletRegistrationBean; } /** * 注册DruidFilter拦截 * * @return */ @Bean public FilterRegistrationBean duridFilterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); Map<String, String> initParams = new HashMap<String, String>(); // 设置忽略请求 initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.setInitParameters(initParams); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } /** * 配置DruidDataSource * * @return * @throws SQLException */ @Bean public DruidDataSource druidDataSource() throws SQLException { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setUsername(userName); druidDataSource.setPassword(password); druidDataSource.setUrl(url); druidDataSource.setMaxActive(100); druidDataSource.setFilters("stat,wall"); druidDataSource.setInitialSize(10); return druidDataSource; } @Bean public SqlSessionFactory sqlSessionFactoryBean() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(druidDataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.mofangge.model,com.mofangge.dto"); Interceptor[] interceptors = {new PageHelper()}; sqlSessionFactoryBean.setPlugins(interceptors); return sqlSessionFactoryBean.getObject(); } public static void main(String[] args) { SpringApplication.run(MfgAgencyApplication.class, args); } } properties文件: #server #server.port=8080 server.port=8081 #server.port=8099 #server.servlet-path=/agency ## log logging.level.org.springframework.web: error logging.level.com.mofangge:info logging.file:mfg-agency.log # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.data.jpa.repositories.enabled=true spring.jpa.database=mysql spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.generate-ddl=false spring.jpa.hibernate.ddl-auto=none spring.jpa.open-in-view=true spring.jpa.show-sql=false 现在遇到的问题是: 实体类中的格式 返回到页面后,字段格式变化了,如下图: 实体: ![图片说明](https://img-ask.csdn.net/upload/201803/08/1520520274_791208.png) 数据库: ![图片说明](https://img-ask.csdn.net/upload/201803/08/1520520307_858101.png) 返回到页面后的值(controller注解了@RestController): ![图片说明](https://img-ask.csdn.net/upload/201803/08/1520520354_282352.png) 第二个字母 应该是大写C 结果变成了小写c。 而且有个现象是: 如果你的字段是 sName 那么前端拿到的是sname 如果你的字段是seName 那么前端拿到的就是seName **不会变化** 也就是说 如果驼峰前字母是2个或2个以上 他就按照原来的格式了,不知道具体是什么原因,求大佬教导。 ps: 我试过很多种方法,只有一种有效果 就是给字段注解 @JsonProperty 但是这种方法会造成我的返回值里会有2个 sname 一个是sname 一个是sName 2个字段都是同样的值 给我一种复制的感觉。。
springBoot整合mybatis时的错,求助!
项目结构![图片说明](https://img-ask.csdn.net/upload/201903/15/1552617152_885756.png) yml配置 ``` spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/zmz username: root password: root mybatis: typeAliasesPackage: Beans mapperLocations: classpath:mappers/*.xml logging: level: mapper: debug ``` 报错信息 ``` java.lang.IllegalStateException: Could not evaluate condition on com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure#dataSource due to org/springframework/boot/web/servlet/ServletRegistrationBean not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake) at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:55) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:102) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:178) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:140) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:333) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:678) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE] at start.Start.main(Start.java:12) [classes/:na] Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/web/servlet/ServletRegistrationBean at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_144] at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_144] at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_144] at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:609) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:521) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:507) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:567) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:683) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:627) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1445) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:975) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry$OptimizedBeanTypeRegistry.addBeanTypeForNonAliasDefinition(BeanTypeRegistry.java:289) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry$OptimizedBeanTypeRegistry.addBeanType(BeanTypeRegistry.java:278) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry$OptimizedBeanTypeRegistry.getNamesForType(BeanTypeRegistry.java:259) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.OnBeanCondition.collectBeanNamesForType(OnBeanCondition.java:182) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:171) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:139) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:113) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-1.3.3.RELEASE.jar:1.3.3.RELEASE] ... 17 common frames omitted Caused by: java.lang.ClassNotFoundException: org.springframework.boot.web.servlet.ServletRegistrationBean at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144] at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144] at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144] ... 37 common frames omitted 2019-03-15 10:27:17.852 INFO 3600 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/resources.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/rt.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jsse.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jce.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/charsets.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jfr.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/access-bridge-64.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/cldrdata.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/dnsns.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/jaccess.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/jfxrt.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/localedata.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/nashorn.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/sunec.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/sunjce_provider.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/sunmscapi.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/sunpkcs11.jar, file:/C:/Program%20Files/Java/jdk1.8.0_144/jre/lib/ext/zipfs.jar, file:/D:/software/workspace/spb/target/classes/, file:/D:/software/repo/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-starter-web/1.3.3.RELEASE/spring-boot-starter-web-1.3.3.RELEASE.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-starter/1.3.3.RELEASE/spring-boot-starter-1.3.3.RELEASE.jar, file:/D:/software/repo/org/springframework/boot/spring-boot/1.3.3.RELEASE/spring-boot-1.3.3.RELEASE.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-starter-logging/1.3.3.RELEASE/spring-boot-starter-logging-1.3.3.RELEASE.jar, file:/D:/software/repo/ch/qos/logback/logback-classic/1.1.5/logback-classic-1.1.5.jar, file:/D:/software/repo/ch/qos/logback/logback-core/1.1.5/logback-core-1.1.5.jar, file:/D:/software/repo/org/slf4j/slf4j-api/1.7.16/slf4j-api-1.7.16.jar, file:/D:/software/repo/org/slf4j/jcl-over-slf4j/1.7.16/jcl-over-slf4j-1.7.16.jar, file:/D:/software/repo/org/slf4j/jul-to-slf4j/1.7.16/jul-to-slf4j-1.7.16.jar, file:/D:/software/repo/org/slf4j/log4j-over-slf4j/1.7.16/log4j-over-slf4j-1.7.16.jar, file:/D:/software/repo/org/springframework/spring-core/4.2.5.RELEASE/spring-core-4.2.5.RELEASE.jar, file:/D:/software/repo/org/yaml/snakeyaml/1.16/snakeyaml-1.16.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-starter-tomcat/1.3.3.RELEASE/spring-boot-starter-tomcat-1.3.3.RELEASE.jar, file:/D:/software/repo/org/apache/tomcat/embed/tomcat-embed-core/8.0.32/tomcat-embed-core-8.0.32.jar, file:/D:/software/repo/org/apache/tomcat/embed/tomcat-embed-el/8.0.32/tomcat-embed-el-8.0.32.jar, file:/D:/software/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/8.0.32/tomcat-embed-logging-juli-8.0.32.jar, file:/D:/software/repo/org/apache/tomcat/embed/tomcat-embed-websocket/8.0.32/tomcat-embed-websocket-8.0.32.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-starter-validation/1.3.3.RELEASE/spring-boot-starter-validation-1.3.3.RELEASE.jar, file:/D:/software/repo/org/hibernate/hibernate-validator/5.2.4.Final/hibernate-validator-5.2.4.Final.jar, file:/D:/software/repo/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar, file:/D:/software/repo/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/D:/software/repo/com/fasterxml/classmate/1.1.0/classmate-1.1.0.jar, file:/D:/software/repo/com/fasterxml/jackson/core/jackson-databind/2.6.5/jackson-databind-2.6.5.jar, file:/D:/software/repo/com/fasterxml/jackson/core/jackson-annotations/2.6.5/jackson-annotations-2.6.5.jar, file:/D:/software/repo/com/fasterxml/jackson/core/jackson-core/2.6.5/jackson-core-2.6.5.jar, file:/D:/software/repo/org/springframework/spring-web/4.2.5.RELEASE/spring-web-4.2.5.RELEASE.jar, file:/D:/software/repo/org/springframework/spring-aop/4.2.5.RELEASE/spring-aop-4.2.5.RELEASE.jar, file:/D:/software/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/D:/software/repo/org/springframework/spring-beans/4.2.5.RELEASE/spring-beans-4.2.5.RELEASE.jar, file:/D:/software/repo/org/springframework/spring-context/4.2.5.RELEASE/spring-context-4.2.5.RELEASE.jar, file:/D:/software/repo/org/springframework/spring-webmvc/4.2.5.RELEASE/spring-webmvc-4.2.5.RELEASE.jar, file:/D:/software/repo/org/springframework/spring-expression/4.2.5.RELEASE/spring-expression-4.2.5.RELEASE.jar, file:/D:/software/repo/org/mybatis/spring/boot/mybatis-spring-boot-starter/1.3.0/mybatis-spring-boot-starter-1.3.0.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-starter-jdbc/1.3.3.RELEASE/spring-boot-starter-jdbc-1.3.3.RELEASE.jar, file:/D:/software/repo/org/apache/tomcat/tomcat-jdbc/8.0.32/tomcat-jdbc-8.0.32.jar, file:/D:/software/repo/org/apache/tomcat/tomcat-juli/8.0.32/tomcat-juli-8.0.32.jar, file:/D:/software/repo/org/springframework/spring-jdbc/4.2.5.RELEASE/spring-jdbc-4.2.5.RELEASE.jar, file:/D:/software/repo/org/springframework/spring-tx/4.2.5.RELEASE/spring-tx-4.2.5.RELEASE.jar, file:/D:/software/repo/org/mybatis/spring/boot/mybatis-spring-boot-autoconfigure/1.3.0/mybatis-spring-boot-autoconfigure-1.3.0.jar, file:/D:/software/repo/org/mybatis/mybatis/3.4.4/mybatis-3.4.4.jar, file:/D:/software/repo/org/mybatis/mybatis-spring/1.3.1/mybatis-spring-1.3.1.jar, file:/D:/software/repo/com/alibaba/druid-spring-boot-starter/1.1.0/druid-spring-boot-starter-1.1.0.jar, file:/D:/software/repo/com/alibaba/druid/1.1.0/druid-1.1.0.jar, file:/D:/software/repo/org/springframework/boot/spring-boot-autoconfigure/1.3.3.RELEASE/spring-boot-autoconfigure-1.3.3.RELEASE.jar] ```
springboot+mybatis(xml模式) 项目 单元测试 报错。
2017-09-01 17:35:21.034 INFO 11212 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.lxhw.module.jbxx.dao.DjKjfCzryDao.getCzry at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:230) at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:48) at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) at com.sun.proxy.$Proxy98.getCzry(Unknown Source) at com.lxhw.module.jbxx.service.DjKjfCzryService.getCzry(DjKjfCzryService.java:47) at com.lxhw.module.jbxx.service.DjKjfCzryService$$FastClassBySpringCGLIB$$30938009.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) at com.lxhw.module.jbxx.service.DjKjfCzryService$$EnhancerBySpringCGLIB$$428d2624.getCzry(<generated>) at com.lxhw.module.jbxx.service.DjKjfCzryServiceTest.searchCzry(DjKjfCzryServiceTest.java:21) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) 这个是报错信息 项目运行正常,就是不能单元测试 初步估计是DjKjfCzryDao.class和DjKjfCzryDao.xml没有匹配上。但是run application是正常的,只有junit的时候有问题 是不是和引入mybais-spring-boot-starter有关系,不能自动去取配置文件了。
Spring Boot+durid+mybatis 怎么实现数据源的主备功能?当A数据源断开后自动切换到B数据源
# 如题: _现在项目有一个需求,数据库服务器是双网卡的。 当A网卡网络坏掉的情况下,软件应该通过B网链接到数据库进行数据操作。 目前项目是用JAVA开发的,使用的是 Spring Boot + druid + mybatis 2019/7/2 今天有 一个思路,就是实现druid的数据源链接断开时间和重连时间, 当数据源断开重连时去判断重连的URL地址是否正常,但是druid的事件有没有大佬使用过???
druid双机备份,当一个数据库挂了, 这时候驱动切换了数据库,这时连接池中还有上一个数据库的连接.该怎么办
springboot + mybatis + druid + postgresql 因为postgresql在驱动中配置双机备份,只要当数据库连接不上, 就会切换数据库, 所以, 当驱动切换了数据库,数据库连接池中还有上一个数据库的连接,这时候用户使用功能的时候,连接池会先用上一个数据库的连接去连接, 这时候前端就会报错, 有什么办法,当驱动切换了数据库的时候, 连接池也重新换一个连接
springboot2.1.8集成druid连接池 无法实现sql监控
![图片说明](https://img-ask.csdn.net/upload/201910/15/1571113606_898290.jpg) sql监控没有数据 连接池配置: initial-size: 10 # 最大连接数 max-active: 50 #最小连接数 min-idle: 10 #获取连接等待超时时间 max-wait: 5000 pool-prepared-statements: true #是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 max-pool-prepared-statement-per-connection-size: 20 validation-query: SELECT 1 FROM DUAL validation-query-timeout: 20000 test-on-borrow: false #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 test-on-return: false #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 test-while-idle: true #建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 time-between-eviction-runs-millis: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 min-evictable-idle-time-millis: 300000 #一个连接在池中最小生存的时间,单位是毫秒 #通过connectionProperties属性来打开mergeSql功能;慢sql记录 connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000 # StatViewServlet配置。(因为暴露的监控信息比较敏感,支持密码加密和访问ip限定) stat-view-servlet: # 是否启用WebStatFilter enabled: true # 访问路径 url-pattern: "/druid/*" # 排除不必要的url exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico" # 监控最大session数,默认是1000 session-stat-max-count: 1000 # 是否启用session的统计功能 session-stat-enable: true # 是否启用监控单个Url调用的sql列表 profile-enable: true # 使druid当前session的用户是谁,session_user_key是你保存到session中的sessionName principalSessionName: session_user_key # 使druid只当当前的user是谁,cookie_user_key是你保存在cookie中的cookieName principalCookieName: cookie_user_key #可以增加访问账号密码【去掉注释就可以】 #login-username: admin #login-password: admin filter: # 监控统计 stat: # 数据库类型 db-type: mysql # 慢SQL log-slow-sql: true # 慢SQL执行时间 slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: true ###试了各种方法sql监控就是没有出来
spring-boot和mybatis配置多数据源,service找不到bean
# 在配置多数据源时候在service层的时候如果只用@Autowired的时候会因为有多个数据源而报错,但当我加上@Qualifier("sqlSessionFactory")的时候又会查不到对应的bean是我的注解写的有问题? 配置文件如下 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 读取数据库连接信息配置 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:db.properties" /> </bean> <!-- 配置数据源连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="100"/> <property name="initialSize" value="5"/> <property name="minIdle" value="5"/> <property name="maxWait" value="60"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 1"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="true"/> <property name="testOnReturn" value="false"/> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> </bean> <!-- 配置数据源管理对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> --> <property name="mapperLocations" value="classpath:com/ocss/sqlmap/*.xml" /> <property name="typeAliasesPackage" value="com.ocss.dao"/> </bean> <!-- 配置数据源自动实装 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ocss.dao" /> <property name="processPropertyPlaceHolders" value="true" /> <!-- <property name="sqlSessionTemplateBeanName" value="sqlSessionFactory" /> --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!-- 配置数据源事务控制 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置数据源连接池2 --> <bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName2}"/> <property name="url" value="${jdbc.url2}"/> <property name="username" value="${jdbc.username2}"/> <property name="password" value="${jdbc.password2}"/> <property name="maxActive" value="100"/> <property name="initialSize" value="5"/> <property name="minIdle" value="5"/> <property name="maxWait" value="60"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 1"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="true"/> <property name="testOnReturn" value="false"/> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> </bean> <!-- 配置数据源管理对象 --> <bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource2" /> <!-- <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> --> <property name="mapperLocations" value="classpath:com/his/sqlmap/*.xml" /> <property name="typeAliasesPackage" value="com.his.dao"/> </bean> <!-- 配置数据源自动实装 --> <bean id="mapperScanner2" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.his.dao" /> <property name="processPropertyPlaceHolders" value="true" /> <property name="sqlSessionTemplateBeanName" value="sqlSessionFactory2" /> <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2" /> --> </bean> <bean id="sqlSession2" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory2" /> </bean> <!-- 配置数据源事务控制 --> <bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource2" /> </bean> <tx:annotation-driven transaction-manager="transactionManager2" /> </beans> ## service如下 @Service public class InfoContentServiceImpl implements InfoContentService { @Autowired //@Qualifier("sqlSessionFactory") private InfoContentDao infoContentDao;
Apache druid的数据源设置了3000个字段的demensions,写入数据的进入内存,可以查询出来,但是数据一直不进行落盘,没有进入segment
Apache druid的数据源设置了3000个字段的demensions,写入数据的进入内存,可以查询出来,但是数据一直不进行落盘,没有进入segment。 查看task的日志也没有保存。
springboot+druid配置无效
使用druid-spring-boot-starter 提供的配置方法,运行之后应用不到druid连接处,而是默认的HikariPool pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.druid</groupId> <artifactId>druid</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>druid</name> <description>测试</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 运行的类 ``` package com.druid; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages="com.alibaba.druid.spring.boot") public class DruidApplication { public static void main(String[] args) { SpringApplication.run(DruidApplication.class, args); } } ```
springboot2.1.4 + jpa + hibernate 使用aop注解形式实现多数据源管理 可能懒加载出现问题求大神解答
最近项目中使用springboot2.1.4 + jpa + hibernate 使用aop注解形式实现多数据源管理,用的就是网上大多数人使用的一套代码,但是我在项目中使用后发现如果配置 spring配置文件 application.yml 中open-in-view: false 跨数据源查询正常,但是保存或者修改失败原因是事务没有提交,一旦把open-in-view改成true则不能跨数据源查询,修改保存正常事务正常提交求解,具体代码如下实现 1. application.yml ``` spring: ## 数据库配置 #datasource: #driver-class-name: com.mysql.jdbc.Driver #url: jdbc:mysql://192.168.101.125:3306/cdv?useSSL=false&characterEncoding=utf-8 #username: root #password: 123456 #url: jdbc:mysql://127.0.0.1:3306/boot-jpa-back-sys2?useSSL=false&characterEncoding=utf-8 #username: root #password: datasource: test1: driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://192.168.101.125:3306/cdv?useSSL=false&characterEncoding=utf-8 username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource test2: driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc-url: jdbc:sqlserver://192.168.101.125:1433;database=Test; username: sa password: Zqvideo123 type: com.alibaba.druid.pool.DruidDataSource ## jpa配置 jpa: show-sql: true hibernate: #ddl-auto: update properties: hibernate.dialect: com.common.mysql.MySQLDialectUTF8 hibernate.format_sql: false open-in-view: false ``` DataSourceAsepct ``` package com.common.db; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Aspect @Component @Order(0) public class DataSourceAsepct { //加载数据源 @Pointcut("@annotation(com.common.db.DataSourceSet)") // @AfterThrowing(pointcut="@annotation(com.common.db.DataSource)", throwing= "error") public void pointCut(){ } @Before("pointCut()") public void before(JoinPoint joinPoint) { Object target = joinPoint.getTarget(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); DataSourceEnum dataSource = DataSourceEnum.DEFAULT; try { Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes()); if (method.isAnnotationPresent(DataSourceSet.class)) { DataSourceSet annotation = method.getAnnotation(DataSourceSet.class); dataSource = annotation.value(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } //实现aop切换数据源 System.out.println("aop切换数据源:" + dataSource.getName()); DataSourceHolder.setDataSource(dataSource); } // @After("pointCut()") @AfterThrowing(pointcut="@annotation(com.common.db.DataSourceSet)", throwing= "error") public void after() { DataSourceHolder.clearDataSource(); String v = DataSourceHolder.getDataSource(); System.out.println(v); } } ``` DataSourceConfig ``` package com.common.db; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.jta.JtaTransactionManager; @Configuration public class DataSourceConfig { //连接数据库db1 @Bean("test1") @ConfigurationProperties("spring.datasource.test1") public DataSource test1() { return DataSourceBuilder.create().build(); } //连接数据库db2 @Bean("test2") @ConfigurationProperties("spring.datasource.test2") public DataSource test2() { return DataSourceBuilder.create().build(); } @Bean("dynamicDataSource") @Primary public DataSource dynamicDataSource() { DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setDefaultTargetDataSource(test1()); Map<Object, Object> dataSourceMap = new HashMap<>(2); dataSourceMap.put(DataSourceEnum.TEST1.getName(), test1()); dataSourceMap.put(DataSourceEnum.TEST2.getName(), test2()); dataSource.setTargetDataSources(dataSourceMap); return dataSource ; } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dynamicDataSource()); } } ``` DataSourceEnum ``` package com.common.db; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum DataSourceEnum { DEFAULT("test1"), TEST1("test1"), TEST2("test2"); private String name; } ``` DataSourceHolder ``` package com.common.db; public class DataSourceHolder { private static final ThreadLocal<String> DS_HOLDER = new ThreadLocal<>(); public static void setDataSource(DataSourceEnum dataSource) { DS_HOLDER.set(dataSource.getName()); } public static String getDataSource() { return DS_HOLDER.get(); } public static void clearDataSource() { DS_HOLDER.remove(); } } ``` DataSourceSet ``` package com.common.db; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface DataSourceSet { //枚举 DataSourceEnum value(); } ``` DynamicDataSource ``` package com.common.db; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { //基于aop切换数据源 System.out.println("dynamic datasource 切换数据源" + DataSourceHolder.getDataSource()); return DataSourceHolder.getDataSource(); } } ``` 测试调用 ``` server层 @Override @DataSourceSet(DataSourceEnum.TEST1) public String test1(Long id) { String s = programRepository.findids(id); System.out.println(s); return s; } @Override @DataSourceSet(DataSourceEnum.TEST2) public String test2(Long id) { String s = testRepository.findids1(id); System.out.println(s); return s; } ``` ``` Controller层 @PostMapping("/test") @ResponseBody public ResultVo test(Long id) { id = 1l; String beProgram1 = programService.test1(id); System.out.println(222); id=2l; String beProgram = testService.test2(id); System.out.println(333); return ResultVoUtil.success(beProgram+beProgram1); } ```
Druid连接Mysql出现错误,create connection SQLException
``` 2020-01-17 23:43:11.284 ERROR 1710 --- [reate-161314577] com.alibaba.druid.pool.DruidDataSource : create connection SQLException, url: jdbc:mysql://192.168.151.130:6666/secondskill?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8, errorCode 1049, state 42000 java.sql.SQLSyntaxErrorException: Unknown database 'secondskill' at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.18.jar:8.0.18] at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1643) ~[druid-1.1.20.jar:1.1.20] at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1709) ~[druid-1.1.20.jar:1.1.20] at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:2715) ~[druid-1.1.20.jar:1.1.20] ``` 这个错误是在我修改Mysql时区后出现的,但是我不能确定是不是修改时区导致的这个问题,这个Mysql是在centos系统上的docker里运行的,在我本机上通过navicat是可以连接上Mysql数据库的,用户名和密码是可以保证正确的.这个是出现的错误码 **errorCode 1049, state 42000**,我曾尝试更换了Mysql连接jar包为5.1.38的也是出现这个错误.程序运行是没有问题的,如果过程中有对数据库的操作的话就会也现这个错误,请问这个问题在那里呢?
java内存溢出问题,不确定哪里出的问题
项目运行的时候出现了内存溢出情况,复现方式无法确定,大概出现了五六次,每次复现的方式都不一样,下面是我用MAT工具分析的dump文件 ![图片说明](https://img-ask.csdn.net/upload/202001/20/1579508231_612899.png) ![图片说明](https://img-ask.csdn.net/upload/202001/20/1579508244_502327.png) 除了hibernate里的那两个对象,其他的1000多万个对象里全是integer类型的对象 这是当时出现的时候产生的异常 ``` 2020-01-17 13:32:55 ERROR [DruidDataSource.java:2469] - create connection SQLException, url: jdbc:mysql://localhost:55060/mcs?useUnicode=true&characterEncoding=utf-8, errorCode 0, state 08S01 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 1 milliseconds ago. The last packet sent successfully to the server was 0 milliseconds ago. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3517) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3417) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3860) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:864) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1707) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1217) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2220) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) at sun.reflect.GeneratedConstructorAccessor118.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323) at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1513) at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1578) at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:2466) Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost. at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2969) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3427) ... 19 more 2020-01-17 13:33:03 ERROR [DiskStorageFactory.java:495] - Disk Write of mcs_preset_rlat failed: java.lang.OutOfMemoryError: GC overhead limit exceeded at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.getBytes(MemoryEfficientByteArrayOutputStream.java:65) at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.serialize(MemoryEfficientByteArrayOutputStream.java:99) at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:405) at net.sf.ehcache.store.disk.DiskStorageFactory.write(DiskStorageFactory.java:384) at net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask.call(DiskStorageFactory.java:485) at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1088) at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1072) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 2020-01-17 13:32:59 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:32:59 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:32:55 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:16 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:27 WARN [SqlExceptionHelper.java:143] - SQL Error: 0, SQLState: null 2020-01-17 13:33:27 ERROR [SqlExceptionHelper.java:144] - wait millis 7401, active 16, maxActive 40, creating 1 2020-01-17 13:33:27 INFO [GetCWRCapHandler.java:114] - 解析录像服务器上报心跳协议过程中出现异常:org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection 2020-01-17 13:33:33 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:33 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:49 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:49 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:49 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:49 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:49 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:53 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:53 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:33:53 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:02 WARN [SqlExceptionHelper.java:143] - SQL Error: 0, SQLState: null 2020-01-17 13:34:02 ERROR [SqlExceptionHelper.java:144] - wait millis 5503, active 18, maxActive 40, creating 1 2020-01-17 13:34:02 INFO [GetCWRCapHandler.java:114] - 解析录像服务器上报心跳协议过程中出现异常:org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection 2020-01-17 13:34:04 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:08 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:12 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:12 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:14 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:14 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:14 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:17 WARN [SqlExceptionHelper.java:143] - SQL Error: 0, SQLState: null 2020-01-17 13:34:17 ERROR [SqlExceptionHelper.java:144] - wait millis 5485, active 19, maxActive 40, creating 1 2020-01-17 13:34:17 INFO [GetCWRCapHandler.java:114] - 解析录像服务器上报心跳协议过程中出现异常:org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [null]; error code [0]; Could not open connection; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection 2020-01-17 13:34:17 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:27 INFO [DeviceCache.java:249] - 设备状态及报警维护过程中出现异常 2020-01-17 13:34:35 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:35 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:42 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:42 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:44 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:44 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:34:52 WARN [SqlExceptionHelper.java:143] - SQL Error: 0, SQLState: null 2020-01-17 13:34:52 ERROR [SqlExceptionHelper.java:144] - wait millis 7301, active 22, maxActive 40, creating 1 2020-01-17 13:34:52 INFO [GetCWRCapHandler.java:114] - 解析录像服务器上报心跳协议过程中出现异常:org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection 2020-01-17 13:34:53 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:35:05 ERROR [DiskStorageFactory.java:495] - Disk Write of mcs_roll_preset failed: java.lang.OutOfMemoryError: GC overhead limit exceeded 2020-01-17 13:35:18 WARN [SqlExceptionHelper.java:143] - SQL Error: 0, SQLState: null 2020-01-17 13:35:18 ERROR [SqlExceptionHelper.java:144] - Error 2020-01-17 13:35:50 WARN [SqlExceptionHelper.java:143] - SQL Error: 0, SQLState: null 2020-01-17 13:35:50 ERROR [SqlExceptionHelper.java:144] - Error 2020-01-17 13:36:13 WARN [SqlExceptionHelper.java:143] - SQL Error: 1205, SQLState: 40001 2020-01-17 13:36:13 ERROR [SqlExceptionHelper.java:144] - Lock wait timeout exceeded; try restarting transaction 2020-01-17 13:36:13 WARN [SqlExceptionHelper.java:143] - SQL Error: 1205, SQLState: 40001 2020-01-17 13:36:24 ERROR [SqlExceptionHelper.java:144] - Lock wait timeout exceeded; try restarting transaction 2020-01-17 13:36:13 WARN [SqlExceptionHelper.java:143] - SQL Error: 1205, SQLState: 40001 2020-01-17 13:37:01 ERROR [SqlExceptionHelper.java:144] - Lock wait timeout exceeded; try restarting transaction 2020-01-17 13:37:43 WARN [DruidDataSource.java:1258] - get connection timeout retry : 1 2020-01-17 13:36:37 WARN [SqlExceptionHelper.java:143] - SQL Error: 1205, SQLState: 40001 2020-01-17 13:36:33 WARN [SqlExceptionHelper.java:143] - SQL Error: 1205, SQLState: 40001 2020-01-17 13:36:22 WARN [SqlExceptionHelper.java:143] - SQL Error: 1205, SQLState: 40001 ``` 现在就是无法确定到底哪里导致的内存溢出?
springboot一共7个jar,在本地idea上面都没问题,但是在服务器,一个jar启动不了
springboot项目,在idea上面正常启动,没有任何问题,但是在测试服务器(linux系统)启动不了,直接初始化数据源后close,各位大神谁可以看下是什么原因不,谢谢! ``` C:\Users\Administrator\Desktop\localJar>java -jar ad_user-0.0.1-SNAPSHOT.jar log4j:WARN No appenders could be found for logger (org.springframework.web.context.support.StandardServletEnvironment). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.1.RELEASE) 2020-01-02 15:59:03.441 INFO 14568 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode! 2020-01-02 15:59:04.626 INFO 14568 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2020-01-02 15:59:04.626 INFO 14568 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29 2020-01-02 15:59:04.639 INFO 14568 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:\Program Files\xftp\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;D:\Program Files\NetSarang\Xshell 6\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;D:\Program Files\GIT\bin;D:\maven\apache-maven-3.3.9\bin\;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;C:\Users\Administrator\AppData\Local\GitHubDesktop\bin;"C:\Program Files\Java\jdk1.8.0_221\bin;C:\Program Files\Java\jdk1.8.0_221\jre\bin;";;.] 2020-01-02 15:59:04.729 INFO 14568 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/user] : Initializing Spring embedded WebApplicationContext 2020-01-02 15:59:05.005 WARN 14568 --- [ost-startStop-1] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources. 2020-01-02 15:59:05.005 INFO 14568 --- [ost-startStop-1] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath. 2020-01-02 15:59:05.032 INFO 14568 --- [ost-startStop-1] c.netflix.config.DynamicPropertyFactory : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@3c432935 2020-01-02 15:59:05.420 INFO 14568 --- [ost-startStop-1] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource 2020-01-02 15:59:05.816 INFO 14568 --- [ost-startStop-1] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited 2020-01-02 15:59:07.798 INFO 14568 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed 2020-01-02 15:59:07.800 INFO 14568 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] ```
Spring+Mybatis+druid 数据库datasource的问题
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [applicationContext-dao.xml]: Invocation of init method failed; nested exception is java.lang.UnsupportedClassVersionError: com/mysql/cj/jdbc/Driver : Unsupported major.minor version 52.0
springboot2.0加入druid后使用的还是Hikari
配置 ``` spring: datasource: type: com.alibaba.druid.pool.DruidDataSource master: jdbcUrl: jdbc:mysql://127.0.0.1:3306/spring_boot_learning?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8 username: root password: root3306 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 初始化大小,最小,最大 initialSize: 5 minIdle: 5 maxActive: 20 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall,log4j # 合并多个DruidDataSource的监控数据 #useGlobalDataSourceStat: true slave: jdbcUrl: jdbc:mysql://127.0.0.1:3306/spring_boot_learning_one?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8 username: root password: root3306 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 初始化大小,最小,最大 initialSize: 5 minIdle: 5 maxActive: 20 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall,log4j # 合并多个DruidDataSource的监控数据 #useGlobalDataSourceStat: true ``` 主数据源配置 ``` @Configuration @MapperScan(basePackages = "indi.xulala.dao.master", sqlSessionTemplateRef = "masterSqlSessionTemplate") public class MasterDataSourceConfig { @Bean(name = "masterDataSource") @ConfigurationProperties(prefix = "spring.datasource.master") @Primary public DataSource setDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "masterTransactionManager") @Primary public DataSourceTransactionManager setTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory setSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return bean.getObject(); } @Bean(name = "masterSqlSessionTemplate") @Primary public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 从数据源配置 ``` @Configuration @MapperScan(basePackages = "indi.xulala.dao.slave", sqlSessionTemplateRef = "slaveSqlSessionTemplate") public class SlaveDataSourceConfig { @Bean(name = "slaveDataSource") @ConfigurationProperties(prefix = "spring.datasource.slave") @Primary public DataSource setDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "slaveTransactionManager") @Primary public DataSourceTransactionManager setTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "slaveSqlSessionFactory") @Primary public SqlSessionFactory setSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return bean.getObject(); } @Bean(name = "slaveSqlSessionTemplate") @Primary public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` application ``` @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @MapperScan(basePackages = {"indi.xulala.dao.master","indi.xulala.dao.slave"}) public class SpringBootLearningApplication { public static void main(String[] args) { SpringApplication.run(SpringBootLearningApplication.class, args); } } ``` 启动日志 ``` 07:48:27.764 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [afterSingletonsInstantiated,434] - Registering beans for JMX exposure on startup 07:48:27.765 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [autodetect,896] - Bean with name 'masterDataSource' has been autodetected for JMX exposure 07:48:27.765 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [autodetect,896] - Bean with name 'slaveDataSource' has been autodetected for JMX exposure 07:48:27.765 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [autodetect,896] - Bean with name 'statFilter' has been autodetected for JMX exposure 07:48:27.772 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [registerBeanInstance,669] - Located MBean 'masterDataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=masterDataSource,type=HikariDataSource] 07:48:27.773 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [registerBeanInstance,669] - Located MBean 'slaveDataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=slaveDataSource,type=HikariDataSource] 07:48:27.774 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [registerBeanInstance,669] - Located MBean 'statFilter': registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter] ``` 测试日志 ``` 07:49:20.159 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,110] - HikariPool-1 - Starting... 07:49:20.694 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,123] - HikariPool-1 - Start completed. 07:49:20.742 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,110] - HikariPool-2 - Starting... 07:49:20.771 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,123] - HikariPool-2 - Start completed. 07:49:20.813 [Thread-3] INFO o.s.w.c.s.GenericWebApplicationContext - [doClose,989] - Closing org.springframework.web.context.support.GenericWebApplicationContext@38831718: startup date [Sat Mar 24 07:49:11 CST 2018]; root of context hierarchy 07:49:20.817 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,381] - HikariPool-2 - Shutdown initiated... 07:49:20.833 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,383] - HikariPool-2 - Shutdown completed. 07:49:20.834 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,381] - HikariPool-1 - Shutdown initiated... 07:49:20.845 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,383] - HikariPool-1 - Shutdown completed. ``` druid-spring-boot-starter版本1.1.9
Kafka实战(三) - Kafka的自我修养与定位
Apache Kafka是消息引擎系统,也是一个分布式流处理平台(Distributed Streaming Platform) Kafka是LinkedIn公司内部孵化的项目。LinkedIn最开始有强烈的数据强实时处理方面的需求,其内部的诸多子系统要执行多种类型的数据处理与分析,主要包括业务系统和应用程序性能监控,以及用户行为数据处理等。 遇到的主要问题: 数据正确性不足 数据的收集主要...
volatile 与 synchronize 详解
Java支持多个线程同时访问一个对象或者对象的成员变量,由于每个线程可以拥有这个变量的拷贝(虽然对象以及成员变量分配的内存是在共享内存中的,但是每个执行的线程还是可以拥有一份拷贝,这样做的目的是加速程序的执行,这是现代多核处理器的一个显著特性),所以程序在执行过程中,一个线程看到的变量并不一定是最新的。 volatile 关键字volatile可以用来修饰字段(成员变量),就是告知程序任何对该变量...
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
GitHub开源史上最大规模中文知识图谱
近日,一直致力于知识图谱研究的 OwnThink 平台在 Github 上开源了史上最大规模 1.4 亿中文知识图谱,其中数据是以(实体、属性、值),(实体、关系、实体)混合的形式组织,数据格式采用 csv 格式。 到目前为止,OwnThink 项目开放了对话机器人、知识图谱、语义理解、自然语言处理工具。知识图谱融合了两千五百多万的实体,拥有亿级别的实体属性关系,机器人采用了基于知识图谱的语义感...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
微信支付崩溃了,但是更让马化腾和张小龙崩溃的竟然是……
loonggg读完需要3分钟速读仅需1分钟事件还得还原到昨天晚上,10 月 29 日晚上 20:09-21:14 之间,微信支付发生故障,全国微信支付交易无法正常进行。然...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
相关热词 c#委托 逆变与协变 c#新建一个项目 c#获取dll文件路径 c#子窗体调用主窗体事件 c# 拷贝目录 c# 调用cef 网页填表c#源代码 c#部署端口监听项目、 c#接口中的属性使用方法 c# 昨天
立即提问