java线程中使用mysql连接查询数据库

在一个一直运行的类中,由于匹配到特定的任务就需要做特定的事,这个步骤我打算直接在当前类中创建一个线程new Thread().start();做操作,然后通过线程的构造函数把数据库连接对象jdbcTemplate传过去直接查数据库对结果做处理,这样做符号规范吗,或者有没有什么更好的方法

1个回答

数据库连接对象共享,应该是可以的。
如果用连接池的话,可以将连接池管理对象共享,每个任务自己通过连接池获取连接去执行任务。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
springboot+mybatis+数据库连接池+mysql
**求助** 我这边有一个springboot的应用,通过浏览器请求后台服务,后台服务通过mybatis查询数据库的数据(数据库服务关闭),由于数据库连接不上连接池会报数据库无法连接,并且重复尝试连接,此时后台服务请求的无法捕获到数据库无法连接的异常整个线程一直处于等待状态,不知道该怎么捕获异常,这个请求资源能够正常释放?
mysql更新数据的同时查询记录
多线程更新mysql数据库表里的某个字段值,更新过程中查询特别慢,有什么好办法解决吗,数据量很小,就几条记录
java多线程高并发下的oracle数据库异常
代码的功能是生成一个随机的序列化的订单号,正常的情况下一个一个跑没问题,在进行压力测试的时候,多线程高并发下,oracle的create语句就会报错,说是 java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sqlSQLException: ORA-00955: 名称已由现有对象使用 求大神看下。 代码如下: ``` package utils.spring; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import utils.Lang; import javax.sql.DataSource; import java.sql.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 序列发生器(可用于高并发、可回收等场景) * * @author lujijiang * */ @Component @ConfigurationProperties(prefix = "seqGenerator") final public class SequenceGenerator implements InitializingBean { interface Atom<T> { T atom(Connection connection) throws Exception; } public static <T> T atom(Connection connection, Atom<T> atom) throws Exception { connection.setAutoCommit(false); connection .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); try { T obj = atom.atom(connection); connection.commit(); return obj; } catch (Exception e) { connection.rollback(); throw e; } } static Map<String, String> createSqlMap = new ConcurrentHashMap<String, String>(); static { createSqlMap .put("h2", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("mysql", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("informix", "CREATE TABLE %s (v$key DECIMAL(16,0) NOT NULL,v$key$ varchar(256),v$seq DECIMAL(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("oracle", "CREATE TABLE %s (v$key NUMBER(16,0) NOT NULL,v$key$ varchar2(256),v$seq NUMBER(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); } static Map<String, String> insertSqlMap = new ConcurrentHashMap<String, String>(); static { insertSqlMap .put("h2", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("mysql", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("informix", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("oracle", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); } /** * 事务模版 */ TransactionTemplate transactionTemplate; /** * 是否使用新事务 */ boolean newTransaction = true; /** * JDBC模版 */ JdbcTemplate jdbcTemplate; /** * 尝试次数(默认10次) */ int tryTime = 10; /** * 数据库类型 */ String databaseType; /** * 表名 */ private String tableName; /** * 容量 */ private int capacity = 25; /** * 步进 */ private int step = 1; /** * 是否可回收序列号 */ protected boolean recyclable; @Autowired public void setTransactionManager( PlatformTransactionManager transactionManager) { if (transactionManager != null) { transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate .setIsolationLevel(TransactionTemplate.ISOLATION_READ_COMMITTED); transactionTemplate .setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED); } } public boolean isNewTransaction() { return newTransaction; } public void setNewTransaction(boolean newTransaction) { this.newTransaction = newTransaction; } public TransactionTemplate getTransactionTemplate() { return transactionTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setDataSource(DataSource dataSource) { if (jdbcTemplate == null) { jdbcTemplate = new JdbcTemplate(dataSource); } } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void setTryTime(int tryTime) { this.tryTime = tryTime; } public void setDatabaseType(String databaseType) { if (databaseType != null) { databaseType = databaseType.trim().toLowerCase(); this.databaseType = databaseType; } } public void setTableName(String tableName) { this.tableName = tableName == null ? null : tableName.trim(); } public void setCapacity(int capacity) { this.capacity = capacity; } public void setStep(int step) { this.step = step < 1 ? 1 : step; } public void setRecyclable(boolean recyclable) { this.recyclable = recyclable; } /** * 创建序列 * * @param name * @param length * @param start * @return */ public String generateSequence(String name, int length, long start) { final long key = generateKey(name); try { return generateSequence(key, length, start, name); } catch (Throwable t) { createSequenceTable();//错误就是定位在这里 int time = tryTime >= 0 ? tryTime : 10000; while (time-- > 0) { try { return generateSequence(key, length, start, name); } catch (Throwable e) { } } throw new RuntimeException("Generate sequence failure", t); } } private long generateKey(String name) { return 10000000000L + name.trim().hashCode(); } /** * 创建序列 * * @param key * @param length * @return */ public String generateSequence(String key, int length) { return generateSequence(key, length, 0); } /** * 创建序列 * * @param key * @return */ public String generateSequence(String key) { return generateSequence(key, 6); } private synchronized void createSequenceTable() { try { jdbcTemplate.execute(new ConnectionCallback<Integer>() { public Integer doInConnection(Connection connection) throws SQLException, DataAccessException { ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null); try { while (rs.next()) { return 1; } } finally { rs.close(); } String createSql = String.format( createSqlMap.get(databaseType), tableName); Statement statement = connection.createStatement(); try { statement.execute(createSql);//错误就是定位在这里 } finally { statement.close(); } return 0; } }); } catch (Throwable t) { throw new RuntimeException(t); } } private String generateSequence(final long key, final int length, final long start, final String name) { if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { return atom(connection, new Atom<String>() { @Override public String atom(Connection connection) throws Exception { if (recyclable) { String no = getRecoveredSequence(connection, key, length); if (no != null) { return no; } } Statement statement = connection.createStatement(); try { String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { Long max = rs.getLong(1); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(connection, deleteSql); insertSql = String.format( insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(connection, deleteSql); } return fillLeftZero(max, length); } } finally { rs.close(); } } finally { statement.close(); } throw new IllegalStateException( SequenceGenerator.this.getClass() .getSimpleName() + "无法获取单号,不可能发生的异常"); } }); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } return getTransactionTemplate().execute( new TransactionCallback<String>() { public String doInTransaction(TransactionStatus ts) { try { if (recyclable) { String no = jdbcTemplate .execute(new ConnectionCallback<String>() { public String doInConnection( Connection connection) throws SQLException, DataAccessException { return getRecoveredSequence( connection, key, length); } }); if (no != null) { return no; } } String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name .replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); Long max = jdbcTemplate.queryForObject(querySql, Long.class); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(deleteSql); insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(deleteSql); } return fillLeftZero(max, length); } catch (Throwable t) { ts.isRollbackOnly(); throw new RuntimeException(t); } } }); } /** * 参数化执行SQL * * @param sql * @param args * @return */ protected int execute(String sql, final Object... args) { return jdbcTemplate.execute(sql, new PreparedStatementCallback<Integer>() { public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } }); } /** * 参数化执行SQL * * @param sql * @param args * @return * @throws SQLException */ protected int execute(Connection conn, String sql, final Object... args) throws SQLException { PreparedStatement ps = conn.prepareStatement(sql); try { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } finally { ps.close(); } } protected String fillLeftZero(Long max, int length) { StringBuilder sb = new StringBuilder(); sb.append(max); if (sb.length() >= length) { return sb.substring(sb.length() - length); } else { for (int i = sb.length(); i < length; i++) { sb.insert(0, '0'); } } return sb.toString(); } /** * 获取已回收的序列 * * @param connection * @param key * @throws SQLException */ protected String getRecoveredSequence(Connection connection, long key, int length) throws SQLException { Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); try { String querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' for update", tableName, key); statement.executeQuery(querySql); querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' order by v$seq asc", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { try { Long min = rs.getLong(2); rs.updateString(3, "1"); rs.updateRow(); return fillLeftZero(min, length); } catch (Throwable ex) { } } } finally { rs.close(); } } finally { statement.close(); } return null; } /** * 回收序列号 * * @param name * @param sequence */ public void recoveredSequence(final String name, final String sequence) { final long key = generateKey(name); final long seq = Long.valueOf(sequence); if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { atom(connection, new Atom<Object>() { public Object atom(Connection connection) throws Exception { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(connection, updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(connection, insertSql); } return null; } }); connection.commit(); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } else { transactionTemplate.execute(new TransactionCallback<Integer>() { public Integer doInTransaction(TransactionStatus status) { try { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(insertSql); } return null; } catch (Throwable t) { status.isRollbackOnly(); throw new RuntimeException(t); } } }); } } public void afterPropertiesSet() throws Exception { if (this.databaseType == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "databaseType")); } if (databaseType != null) { if (!createSqlMap.containsKey(databaseType)) { throw new IllegalStateException(String.format( "Unsupported database type:%s", databaseType)); } } if (this.jdbcTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' or '%s' is required", "dataSource", "jdbcTemplate")); } if (this.tableName == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "tableName")); } if (!tableName.matches("[a-zA-Z_][a-zA-Z0-9_]*") || tableName.length() > 16) { throw new IllegalStateException(String.format( "Illegal tableName:%s", tableName)); } if (!this.newTransaction) { if (this.transactionTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "transactionManager")); } } } } ``` java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:272) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:202) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:227) at cart.service.service.OrderService.generateOrderNo(OrderService.java:806) at cart.service.service.OrderService.saveVirtualGoodsToOrder(OrderService.java:220) at cart.service.service.OrderService$$FastClassBySpringCGLIB$$19f99be7.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) 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:281) 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:655) at cart.service.service.OrderService$$EnhancerBySpringCGLIB$$feb8eef.saveVirtualGoodsToOrder(<generated>) at cart.service.apiImpl.OrderMainApiImpl.saveVirtualGoodsToOrder(OrderMainApiImpl.java:223) at cart.service.apiImpl.OrderMainApiImpl$$FastClassBySpringCGLIB$$fa3518e.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) at cart.service.apiImpl.OrderMainApiImpl$$EnhancerBySpringCGLIB$$497f044.saveVirtualGoodsToOrder(<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 com.weibo.api.motan.rpc.DefaultProvider.invoke(DefaultProvider.java:57) at com.weibo.api.motan.rpc.AbstractProvider.call(AbstractProvider.java:47) at com.weibo.api.motan.filter.AccessLogFilter.filter(AccessLogFilter.java:56) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at utils.rpc.motan.filter.OpenEntityManagerInMotanFilter.filter(OpenEntityManagerInMotanFilter.java:171) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at com.weibo.api.motan.transport.ProviderMessageRouter.call(ProviderMessageRouter.java:96) at com.weibo.api.motan.transport.ProviderProtectedMessageRouter.call(ProviderProtectedMessageRouter.java:79) at com.weibo.api.motan.transport.ProviderMessageRouter.handle(ProviderMessageRouter.java:91) at com.weibo.api.motan.transport.support.DefaultRpcHeartbeatFactory$HeartMessageHandleWrapper.handle(DefaultRpcHeartbeatFactory.java:82) at com.weibo.api.motan.transport.netty.NettyChannelHandler.processRequest(NettyChannelHandler.java:139) at com.weibo.api.motan.transport.netty.NettyChannelHandler.access$000(NettyChannelHandler.java:47) at com.weibo.api.motan.transport.netty.NettyChannelHandler$1.run(NettyChannelHandler.java:116) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:360) at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:247) ... 39 more Caused by: java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288) at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:210) at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:961) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190) at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1726) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1696) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:264) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:247) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:353) ... 40 more
mysql中用三个线程把表test中的数据取出来,怎么写?
mysql中用三个线程把数据库test表jsoup中的数据取出来,怎么写呀?
在Android Studio中,用jdbc连接MySQL连不上
网上的很多方法都试过,还是不行,各位大神帮我看下什么原因。 目前排除的原因: 1.在单元测试中可以连接成功,并获得数据。所以数据库、连接格式应该没问题。 2.connect-java包试了好几个版本都不行。 3.在Activity中连接不上,但我已经放在新的线程中了,而且用好几种开启新线程的方式试过。 以下是代码 ``` public class MainActivity extends AppCompatActivity { private Connection conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(){ @Override public void run() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://rm-bp1p408m8ey1z7ndv4o.mysql.rds.aliyuncs.com/mysql_data", "myroot", "Kwkx12345678"); System.err.println(conn); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }.start(); } } ``` Locat输出: ![图片说明](https://img-ask.csdn.net/upload/201811/28/1543372019_611452.png) 错误提示,百度上搜了一下也没有 Caused by: java.lang.ClassNotFoundException: Didn't find class "java.sql.SQLType" on path: DexPathList[[zip file "/data/app/com.example.administrator.
SSM框架在tomcat7下跑一段时间后抛异常,怀疑是Mysql 8小时连接问题。
框架是Spring+SpringMVC+MyBatis 在Tomcat7上发布后跑大约四个小时后会抛一次异常,但是能正常访问 配置文件: proxool.prototypeCount=5 proxool.maximumActiveTime=300000 proxool.maximumConnectionLifetime=18000000 proxool.minimumConnectionCount=5 proxool.maximumConnectionCount=40 proxool.alias=lvseu proxool.simultaneous-build-throttle=20 proxool.prototype-count=2 proxool.houseKeepingTestSql=select CURRENT_DATE proxool.hourseKeepingSleepTime=30000 <property name="driver" value="${connection.driver_class}" /> <property name="driverUrl" value="${connection.url}" /> <property name="user" value="${connection.username}" /> <property name="password" value="${connection.password}" /> <!-- 测试的SQL执行语句 --> <property name="houseKeepingTestSql" value="${proxool.houseKeepingTestSql}"/> <!-- 最少保持的空闲连接数 (默认2个) --> <property name="prototypeCount" value="${proxool.prototypeCount}" /> <!-- 最大活动时间(超过此时间线程将被kill,默认为5分钟) --> <property name="maximumActiveTime" value="${proxool.maximumActiveTime}" /> <!-- 最小连接数 (默认2个) --> <property name="minimumConnectionCount" value="${proxool.minimumConnectionCount}" /> <!-- 最大连接数 (默认10个) --> <property name="maximumConnectionCount" value="${proxool.maximumConnectionCount}" /> <!-- 连接最长时间(默认为4个小时) --> <property name="maximumConnectionLifetime" value="${proxool.maximumConnectionLifetime}" /> <!-- 数据库别名 --> <property name="alias" value="${proxool.alias}" /> <!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒) --> <property name="houseKeepingSleepTime" value="${proxool.hou rseKeepingSleepTime}" /> 抛的异常为: 2017-08-10 03:20:22 [Prototyper] ERROR org.logicalcobwebs.proxool.lvseu - Prototype com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up. 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:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2270) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:723) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) 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:406) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282) at java.sql.DriverManager.getConnection(DriverManager.java:571) at java.sql.DriverManager.getConnection(DriverManager.java:187) at org.logicalcobwebs.proxool.DefaultConnectionBuilder.buildConnection(DefaultConnectionBuilder.java:39) at org.logicalcobwebs.proxool.Prototyper.buildConnection(Prototyper.java:159) at org.logicalcobwebs.proxool.Prototyper.sweep(Prototyper.java:102) at org.logicalcobwebs.proxool.PrototyperThread.run(PrototyperThread.java:44) Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 0 ms 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:406) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:335) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2194) ... 15 more Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.<init>(Socket.java:425) at java.net.Socket.<init>(Socket.java:241) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:253) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:284) ... 16 more 2017-08-10 03:20:46 [Prototyper] ERROR org.logicalcobwebs.proxool.lvseu - Prototype com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up. 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:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2270) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:723) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) at sun.reflect.GeneratedConstructorAccessor57.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:406) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282) at java.sql.DriverManager.getConnection(DriverManager.java:571) at java.sql.DriverManager.getConnection(DriverManager.java:187) at org.logicalcobwebs.proxool.DefaultConnectionBuilder.buildConnection(DefaultConnectionBuilder.java:39) at org.logicalcobwebs.proxool.Prototyper.buildConnection(Prototyper.java:159) at org.logicalcobwebs.proxool.Prototyper.sweep(Prototyper.java:102) at org.logicalcobwebs.proxool.PrototyperThread.run(PrototyperThread.java:44) Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 0 ms 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:406) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:335) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2194) ... 14 more Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.<init>(Socket.java:425) at java.net.Socket.<init>(Socket.java:241) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:253) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:284) ... 15 more
单线程循环假死,纠结了一星期了,求指导
现在我正在维护一个派单系统,派单的业务逻辑是新起了一个线程,这个派单线程并没有 用到线程池之类的技术,就是一个很简单的new Thread().start(),然后有一个监听线程观察 该线程是否存活,如果不存活就重新再创建一个派单线程,但是现在有一个奇怪的问题,就是 运行大概一天左右,派单线程就会出现假死状态,但是通过ThreadDump发现该线程的状态 是Running,而每次派单线程都卡在一个Hibernate的get查询上,并且ThreadDump发现在该 线程上有获取数据库(mysql)collection的lock,求各位大神指导一下。 线程卡在这一条语句上:newMetaData=HibernateTemplateEx.getInstance().get(OdMetaData.class, busDate); ThreadDump信息是: "AutoAssignerThread_50" - Thread t@84 java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:114) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:161) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:189) - locked <3a396c81> (a com.mysql.jdbc.util.ReadAheadInputStream) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3163) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3620) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3609) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4160) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2828) - locked <1002a704> (a com.mysql.jdbc.JDBC4Connection) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2777) at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1651) - locked <1002a704> (a com.mysql.jdbc.JDBC4Connection) at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208) at org.apache.commons.dbcp.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:658) at org.apache.commons.dbcp.PoolableConnectionFactory.validateObject(PoolableConnectionFactory.java:635) at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:991) at org.apache.commons.dbcp.AbandonedObjectPool.borrowObject(AbandonedObjectPool.java:79) at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1700) at org.hibernate.loader.Loader.doQuery(Loader.java:801) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) at org.hibernate.loader.Loader.loadEntity(Loader.java:2037) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76) at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3294) at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496) at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477) at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998) at org.springframework.orm.hibernate3.HibernateTemplate$1.doInHibernate(HibernateTemplate.java:519) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:512) at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:506) at net.xiaofei.workflow.assignment.autodecider.OdParameterCacheHelper.checkOdStatus(OdParameterCacheHelper.java:307) at net.xiaofei.workflow.assignment.autodecider.WorkFlowCaseDistributeThread.run(WorkFlowCaseDistributeThread.java:63) Locked ownable synchronizers: - None
多线程读数据库操作,为什么我的代码执行起来比原来还慢呢
/** * 查询 应用系统 各表的记录总数 * * @param url 数据源地址 * @param userName 数据源登陆用户名 * @param password 数据源密码 * @param tableNames 表名 List * @return Map < 表名,表下数据行数> */ static class CountThread implements Runnable{ CountThread(String tableName){ this.tableName=tableName; } static void setConnection(Connection connection) { CountThread.connection = connection; } static void setReMap(ConcurrentHashMap map){ CountThread.reMap=map; } static void setThreadCount(CountDownLatch countDownLatch) { CountThread.countDownLatch = countDownLatch; } private static CountDownLatch countDownLatch; private static ConcurrentHashMap<String,String> reMap; private static Connection connection; private String tableName; @Override public void run() { String sql = "SELECT COUNT(1) num FROM " + tableName; System.out.println(sql); try { PreparedStatement stmt = connection.prepareStatement(sql); ResultSet tablesRest = stmt.executeQuery(); while (tablesRest.next()) { String count = tablesRest.getString("num"); reMap.put(tableName, count); } tablesRest.close(); tablesRest = null; countDownLatch.countDown(); } catch (SQLException e) { log.error(e.getMessage()); reMap.put(tableName, "0"); } } } public static Map<String, String> conutRows(String url, String userName, String password, List<String> tableNames) { int size=tableNames.size(); Date start=new Date(); ConcurrentHashMap<String, String> reMap = new ConcurrentHashMap<>(size); CountDownLatch countDownLatch=new CountDownLatch(size); try (Connection connection = DriverManager.getConnection(url, userName, password)) { CountThread.setConnection(connection); CountThread.setReMap(reMap); CountThread.setThreadCount(countDownLatch); for(String tableName:tableNames){ CountThread thread = new CountThread(tableName); thread.run(); } countDownLatch.await(); // sql.append(" SELECT "); // for (String tableName : tableNames) { // sql.append(" " + tableName + "b.num " + tableName + "a ,"); //字符串拼接 表名+a 拼接成表别名 // } // // //删除多余的一个 , // sql.deleteCharAt(sql.length() - 1); // sql.append(" FROM "); // //子查询 ,分别统计表字段数 // for (String tableName : tableNames) { // sql.append(" ( SELECT COUNT(*) num FROM "); // sql.append(tableName); // sql.append(" ) " + tableName + "b ,"); // } // //删除多余的一个 , // sql.deleteCharAt(sql.length() - 1); // System.out.println(sql); // //使用sql语句进行查询获取结果集 // PreparedStatement stmt = connection.prepareStatement(sql.toString()); // ResultSet tablesRest = stmt.executeQuery(); // //对结果进行遍历,此处结果集实际应只有一行数据 // while (tablesRest.next()) { // for (String tableName : tableNames) { // String count = tablesRest.getString(tableName + "a"); // reMap.put(tableName, count); // } // } // tablesRest.close(); // tablesRest = null; } catch (Exception e) { log.error(e.getMessage()); throw new RuntimeException("数据源连接失败"); } Date end=new Date(); long costTime = (end.getTime()-start.getTime()); System.out.println("******************************************"+costTime+"**************************"); return reMap; }
mysql数据库1主多备,这个多备是为了解决什么问题
1:如果多个线程对单张表读取,跟单个线程对单标读取效率会差不多嘛, 因为读数据库是没加锁的,如果有区别,是因为哪方面呢,io还是网络还是cpu还是硬盘。 2: 读写分离 分1主1备,1主多备,想问下,多备是为了解决什么问题呢?
DruidDataSource 配置mysql,启动报错,求大神指点
地址信息: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/order?characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456 jdbc.initSize=5 jdbc.maxActive=10 jdbc.maxIdle=5 jdbc.minIdle=2 jdbc.maxWait=1000 <!-- 配置数据源 --> <bean id="dataSourceone" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <!-- 数据库基本信息配置 --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接数量 --> <property name="initialSize" value="${jdbc.initSize}" /> <!-- 最大并发连接数 --> <property name="maxActive" value="${jdbc.maxActive}" /> <!-- 最大空闲连接数 --> <property name="maxIdle" value="${jdbc.maxIdle}" /> <!-- 最小空闲连接数 --> <property name="minIdle" value="${jdbc.minIdle}" /> <!-- 配置获取连接等待超时的时间 ms --> <property name="maxWait" value="${jdbc.maxWait}" /> <!-- 牺牲效率,避免活锁 --> <property name="useUnfairLock" value="false" /> <!-- 超过时间限制是否回收 未归还(调用close)的连接 --> <property name="removeAbandoned" value="false" /> <!-- 超时回收限制多长;没有批量处理需求,设短一点,单位 秒 --> <property name="removeAbandonedTimeout" value="180" /> <!-- 用来检测连接是否有效的sql,要求是一个查询语句--> <property name="validationQuery" value="SELECT 1 FROM dual" /> <!-- 空闲的时候检测(空闲时间超过下面的值) --> <property name="testWhileIdle" value="true" /> <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnBorrow" value="false" /> <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnReturn" value="false" /> <!-- Destroy线程检测是否关闭连接的间隔,同时也是空闲检测的判断依据,单位 毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="600000" /> <!--属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防御SQL注入的filter:wall--> <property name="filters" value="filter:wall" /> </bean> 启动报错:org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'root'@'122.225.88.154' (using password: YES) 122.225.88.154都不知道是哪里的地址,我已经蒙了,求大神指点
用struts1.2+tomcat5.5+mysql5.1+c3p0连接池开发 出现死机现象
用struts1.2+tomcat5.5+mysql5.1+c3p0连接池开发 出现死机现象 各位朋友,向大家请教一下,我们用struts1.2+tomcat5.5+mysql5.1+c3p0连接池开发一个web应用网站。 现在我们遇到的问题是:现有已经开发的几个模块,部署到linux服务器上,服务器使用的tomcat5.5,运行一段时间就会出现死机的现象,不能登陆及查询(即:数据库操作无响应),刚开始我们初步判断是连接池的原因(因为我们连接池用的单例模式,之前由于考虑不全,出现了两个连接池对象),但是后面我们已经修改了连接池,只有一个连接池对象,再发布测试还是出现这个现象。我们还是不能确定问题出现在哪里, 只是怀疑连接池的问题,我们又做了修改(将c3p0 连接池修改为struts1.2的数据源配置),再次发布到服务器上测试,还是出现相同的问题。 现在我们能推断的问题原因有以下几种情况: 1.连接池问题 (不能确定,应为我们修改了两次连接池,还是出现相同的问题) 2.tomcat 死掉 (不能确定,网上查找了资料,已经修改了tomcat启动参数 设置jvm 的虚拟内存: set JAVA_OPTS=-Xms512m -Xmx512m) 3.mysql 数据库死掉 (不能确定,如果是数据库服务器死掉,但是通过mysql的客户端可以正常操作查询等一些操作) [b]问题补充:[/b] 补充1:Connection,statement都是在应该关闭的地方关闭了的 补充2:没有使用hibernate 补充3:编译没有报错 [b]问题补充:[/b] 补充:程序能够运行一段时间,大概20分钟左右,然后才数据库操作无响应 [b]问题补充:[/b] 我们程序里有两个线程、每隔15分钟扫描一次数据库中表,同时还有用户不停的访问!!麻烦你能否给一个连接池的配置信息!谢谢!!
tomcat shutdown 的时候进程无法关闭,初查是线程池导致的,但未找到解决方案
tomcat执行 shutdown.sh, 服务是关闭了,但是ps -ef仍然能看到相关进程, 导致进程不断增多(不要和我说kill -9 ), 查看tomcat 的 catalina.out 日志, 发现如下日志 ``` 26-Jun-2019 19:43:45.248 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [transaction_agent] registered the JDBC driver [com.alibaba.druid.proxy.DruidDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 26-Jun-2019 19:43:45.248 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [transaction_agent] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 26-Jun-2019 19:43:45.249 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [transaction_agent] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: java.lang.Object.wait(Native Method) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143) com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:41) 26-Jun-2019 19:43:45.250 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [transaction_agent] appears to have started a thread named [pool-1-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745) 26-Jun-2019 19:43:45.251 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [transaction_agent] appears to have started a thread named [pool-7-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745) 26-Jun-2019 19:43:45.252 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [transaction_agent] appears to have started a thread named [pool-1-thread-2] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745) 26-Jun-2019 19:43:45.253 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [transaction_agent] appears to have started a thread named [pool-7-thread-2] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745) ``` 可以看到有两个警告,第一个是数据库连接无法释放,第二个看着是线程池的 问题。我尝试将线程池相关代码注册掉。 发布,然后shutdown.sh ,发现进程 可以正常关闭。所以初步判定是线程池的这个问题导致的进程无法停止。 线程池伪代码如下 ``` public class AA { ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); private String handleDyPosp(String s) throws Exception { DCallable dCallable = new DCallable(s); FutureTask<String> futureTask = new FutureTask(dCallable); executor.executor(futureTask); String s = futureTask.get(50,TimeUnit.SECONDS); } ``` 求解决方案
c3p0关于mysql8小时的问题
jar包:c3p0-0.9.5-pre6.jar mchange-commons-java-0.2.6.3.jar 背景:以前在使用ORM框架的情况下,使用连接池没出现过空闲连接超时的问题,现在新建个项目没什么框架,使用c3p0,代码如下: [code="java"] private static ComboPooledDataSource ds = null; static { try { ds = new ComboPooledDataSource(); ds.setDriverClass(Constant.DRIVER_CLASS_NAME); ds.setJdbcUrl(Constant.URL); ds.setUser(Constant.USERNAME); ds.setPassword(Constant.PASSWORD); ds.setMaxPoolSize(40); ds.setMinPoolSize(5); ds.setAutomaticTestTable("C3P0TestTable"); ds.setIdleConnectionTestPeriod(1800); ds.setTestConnectionOnCheckin(true); ds.setTestConnectionOnCheckout(true); ds.setMaxIdleTime(25000); } catch (PropertyVetoException e) { gLog.error("ComboPooledDataSource", e); } } public static synchronized Connection getConn() { Connection con = null; try { con = ds.getConnection(); } catch (SQLException e1) { gLog.error("getConn", e1); } return con; } [/code] [color=red]有个线程用 getConn()获取连接后,长时间不进行数据库操作,隔天触发数据库操作时会报异常[/color] [code="java"] com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Software caused connection abort: socket write error STACKTRACE: java.net.SocketException: Software caused connection abort: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:136) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2637) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1554) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665) at com.mysql.jdbc.Connection.execSQL(Connection.java:3176) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1153) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1266) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:144) ** END NESTED EXCEPTION ** Last packet sent to the server was 0 ms ago. at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2652) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1554) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665) at com.mysql.jdbc.Connection.execSQL(Connection.java:3176) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1153) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1266) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:144) [/code] 有个线程一直有进行数据库操作,则正常,因此判断是MYSQL8小时问题。但是代码里几个重要属性已经配置了,是否哪里还漏了,错了。 求教!
各位大神,今天面试游戏公司:面试官问:
1. 若有1000台数据库服务器,如何将一个Excel表的内容以最高效的方式存入这1000数据库服务器中(前提是这1000台数据库都创建了相同的表Excel,希望大家给出一个)具体的解决方案,应该是多线程设计等等,就是思想要能够说的明白 ,如果能具体那更好了,谢谢了,数据库是Mysql的,用JAVA实现。 哪位大神有思路?
androidstudio为啥连不上mysql呀,老报如下错
源码: ``` bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.out.println("进入点击事件!!!!!!!!!"); new Thread(new Runnable(){ public void run(){ try { System.out.println("进入线程!!!!!!!!"); System.out.println("开始加载驱动"); Class.forName("com.mysql.jdbc.Driver"); System.out.println("驱动加载完成"); java.sql.Connection cn= DriverManager.getConnection( "jdbc:mysql://192.168.0.106:3306/test","root", "root"); System.out.println("链接数据库"); String sql="select name from androidtest"; Statement st=(Statement)cn.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()){//读表mytable中的每一列 String mybook=rs.getString("name ");//读取的是B_Name这一列,传给mybook Log.i("MainActivity",mybook); } cn.close();//一定要关闭 st.close(); rs.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }).start(); } ``` 报错信息: ``` 2019-08-13 16:04:24.442 29017-29017/com.example.androidmysqltext001 I/System.out: 进入点击事件!!!!!!!!! 2019-08-13 16:04:24.447 29017-29418/com.example.androidmysqltext001 I/System.out: 进入线程!!!!!!!! 2019-08-13 16:04:24.447 29017-29418/com.example.androidmysqltext001 I/System.out: 开始加载驱动 2019-08-13 16:04:24.542 29017-29036/com.example.androidmysqltext001 I/zygote64: Do partial code cache collection, code=30KB, data=21KB 2019-08-13 16:04:24.542 29017-29036/com.example.androidmysqltext001 I/zygote64: After code cache collection, code=26KB, data=20KB 2019-08-13 16:04:24.542 29017-29036/com.example.androidmysqltext001 I/zygote64: Increasing code cache capacity to 128KB 2019-08-13 16:04:24.608 29017-29418/com.example.androidmysqltext001 I/System.out: 驱动加载完成 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1127) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2502) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2539) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:219) 2019-08-13 16:06:31.922 29017-29418/com.example.androidmysqltext001 W/System.err: at com.example.androidmysqltext001.MainActivity$1$1.run(MainActivity.java:33) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.lang.Thread.run(Thread.java:784) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: Caused by: java.net.ConnectException: failed to connect to /192.168.0.106 (port 3306) from /:: (port 51602): connect failed: ETIMEDOUT (Connection timed out) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:138) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:129) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:357) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:201) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:183) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.Socket.connect(Socket.java:616) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.Socket.connect(Socket.java:565) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.Socket.<init>(Socket.java:445) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at java.net.Socket.<init>(Socket.java:248) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:258) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: ... 14 more 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at libcore.io.Linux.connect(Native Method) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:126) 2019-08-13 16:06:31.923 29017-29418/com.example.androidmysqltext001 W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:152) 2019-08-13 16:06:31.924 29017-29418/com.example.androidmysqltext001 W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:130) 2019-08-13 16:06:31.924 29017-29418/com.example.androidmysqltext001 W/System.err: ... 25 more ```
自己封装了一个线程池,求大神帮忙看下有没有安全方面的问题
自己封装的一个jdbc,给jdbc增加了一个连接池,但是不知道有没有问题,所以让大神们帮忙看下,我写的这个线程池有没有问题 ``` package tool; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Jdbc { //连接池中的连接 private Connection conn; private ResultSet rs; private ResultSetMetaData md; private PreparedStatement ps; private JSONArray list; private JSONObject map; private String classpath = getClass().getResource("/").getPath(); private String path = classpath + "jdbc.properties"; private BlockingQueue<Connection> connections = new LinkedBlockingQueue<>(); public Jdbc(){} /** * 初始化Jdbc连接池 * @param poolSize 连接池大小 * @throws IOException * @throws ClassNotFoundException * @throws SQLException * @throws InterruptedException */ public void initJdbcPool() throws IOException, ClassNotFoundException, SQLException, InterruptedException { FileInputStream fis = new FileInputStream(path); Properties prop = new Properties(); prop.load(fis); String url = prop.getProperty("db.url"); String user = prop.getProperty("db.user"); String psw = prop.getProperty("db.password"); Integer connectionNum = Integer.parseInt(prop.getProperty("connectionNum")); Class.forName(prop.getProperty("driverClass")); for (int i = 0; i < connectionNum; i++) { //获取数据库的连接 Connection dbConn = DriverManager.getConnection(url, user, psw); //System.out.println(dbConn); connections.put(dbConn); } } public void destroyJdbcPool() { connections.clear(); } /** * 从连接池中获取链接 * @return * @throws InterruptedException */ private Connection getConnection() throws InterruptedException { return connections.take(); } /** * 把连接放回到连接池中,并关闭声明对象和结果集对象 * @param connection 连接 * @param ps 声明对象 * @param rs 结果集对象 * @throws SQLException * @throws InterruptedException */ private void backConnection(Connection connection,PreparedStatement ps,ResultSet rs) throws SQLException, InterruptedException { if(ps!=null) ps.close(); if(rs!=null) rs.close(); connections.put(connection); } /** * 执行dml操作 * @param sql sql语句 * @param objs 参数对象 * @return */ public boolean dml(String sql, Object... objs) { try { conn = getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { ps.setObject(i+1, objs[i]); } int flg = ps.executeUpdate(); if(flg==1) { return true; } } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally { try { backConnection(conn,ps,rs); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } return false; } /** * 全查 * @param sql * @param objs * @return */ public JSONArray find(String sql,Object...objs){ list = new JSONArray(); try { conn = getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < objs.length; i++) { ps.setObject(i+1, objs[i]); } rs = ps.executeQuery(); md = rs.getMetaData(); while (rs.next()) { map = new JSONObject(); for (int i = 1; i <= md.getColumnCount(); i++) { String key = md.getColumnName(i); Object value = rs.getObject(i); map.put(key, value); } list.add(map); } } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally { try { backConnection(conn,ps,rs); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } return list; } /** * 单查 * @param sql * @param objs * @return */ public JSONObject findOne(String sql,Object...objs){ JSONArray list = find(sql,objs); if(list!=null) { if(list.size()>0) { return list.getJSONObject(0); } } return null; } /** * 添加 * @param sql * @param objs * @return */ public boolean add(String sql,Object...objs) { return dml(sql, objs); } /** * 修改 * @param sql * @param objs * @return */ public boolean mod(String sql,Object...objs){ return dml(sql, objs); } /** * 删除 * @param sql * @param objs * @return */ public boolean del(String sql,Object...objs){ return dml(sql, objs); } } ``` jdbc.properties ``` db.url=jdbc:mysql://127.0.0.1:3306/juser db.user=root db.password=root driverClass=com.mysql.jdbc.Driver connectionNum=30 ```
有大佬有Java swing/matisse form仿QQ小项目吗?
我想要份Java swing/matisse form仿QQ的小项目,最近在学习MySQL数据库,多线程,socket和swing/matisse form图形开发,想要一份资源来做期末大作业
java.sql.SQLException: "Too many connections"
org.hibernate.exception.JDBCConnectionException: Cannot open connection OperateDatabase.java queryAll(String hql)查询结果出来啦 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1577) at org.hibernate.loader.Loader.doQuery(Loader.java:696) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312) at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723) at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165) at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175) at hibernate.OperateDatabase.querySql(OperateDatabase.java:128) at socket.Server$1.run(Server.java:225) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException: Data source rejected establishment of connection, message from server: "Too many connections" at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1018) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2568) at com.mysql.jdbc.Connection.<init>(Connection.java:1485) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) ... 15 more Exception in thread "Thread-27" java.lang.NullPointerException at socket.Server$1.run(Server.java:226) at java.lang.Thread.run(Unknown Source) ClientThread.java线程睡眠1000毫秒=1秒 ClientThread.java从客户端发来的聊天内容:{"actiontype":"1","receverName":"192.168.0.107","msgType":false,"senderName":"192.168.0.108","chatDate":"2017-03-03 18:21:08"} ClientThread.java动作类型1 Exception in thread "Thread-25" org.hibernate.exception.JDBCConnectionException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1577) at org.hibernate.loader.Loader.doQuery(Loader.java:696) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at hibernate.OperateDatabase.query(OperateDatabase.java:87) at chat.ClientThread.run(ClientThread.java:111) Caused by: java.sql.SQLException: Data source rejected establishment of connection, message from server: "Too many connections" at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1018) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2568) at com.mysql.jdbc.Connection.<init>(Connection.java:1485) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) ... 15 more hibernate.hbm.xml文件内容,注释部分是连接池,但貌似使用也不管事 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- mysql 数据库驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- mysql 数据库名 myandroid 端口3306 --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myandroid?useUnicode=true&amp;characterEncoding=utf-8</property> <!-- 数据的登录用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库的登录秘密 --> <property name="hibernate.connection.password">admin</property> <!-- 下面这一行很重要, 如果hibernate.connection.provider_class没有定义,就会使用内置的连接池,所以如果不想用hibernate内置的连接池,下面这一行必须要写的 --> <!-- <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.timeout">120</property> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">120</property> <property name="hibernate.c3p0.acquire_increment">2</property> --> <!-- 方言:为每一种数据库提供适配器,方便转换 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 2,其他配置 --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 所有的表映射XML文件必须在此录入 导入映射文件--> <mapping resource="hibernate/Customer.hbm.xml"/> <mapping resource="hibernate/ChatLog.hbm.xml"/> <mapping resource="hibernate/ChatMessage.hbm.xml"/> <mapping resource="hibernate/Pitch.hbm.xml"/> </session-factory> </hibernate-configuration>
java事务下并发问题怎么搞
现在业务中在实现类serviceImpl.aaaa()方法(事务在该方法上)中有相关业务 业务大概就是 查库中字段sta='R'的数据--》处理逻辑--》修改数据将字段sta改为='I' 现在出现得问题就是多个线程进入后 多个线程同时去请求,**在查数据过程中由于并发获取到了同样的数据** 然后再通过同样逻辑后 去update数据是就发生了相互覆盖得情况,后执行得把前面执行的给了覆盖了,最终相当于数据中只有一条修改语句而不是多条。 各位这种要怎么解决。
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
面试官问我:什么是消息队列?什么场景需要他?用了会出现什么问题?
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
8年经验面试官详解 Java 面试秘诀
作者 |胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。 Java程序员准备和投递简历的实...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观...
MyBatis研习录(01)——MyBatis概述与入门
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis原本是apache的一个开源项目iBatis, 2010年该项目由apache software foundation 迁移到了google code并改名为MyBatis 。2013年11月MyBatis又迁移到Github。
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip installselenium -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ ...
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca...
Python爬虫精简步骤1 获取数据
爬虫,从本质上来说,就是利用程序在网上拿到对我们有价值的数据。 爬虫能做很多事,能做商业分析,也能做生活助手,比如:分析北京近两年二手房成交均价是多少?广州的Python工程师平均薪资是多少?北京哪家餐厅粤菜最好吃?等等。 这是个人利用爬虫所做到的事情,而公司,同样可以利用爬虫来实现巨大的商业价值。比如你所熟悉的搜索引擎——百度和谷歌,它们的核心技术之一也是爬虫,而且是超级爬虫。 从搜索巨头到人工...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东...
破14亿,Python分析我国存在哪些人口危机!
一、背景 二、爬取数据 三、数据分析 1、总人口 2、男女人口比例 3、人口城镇化 4、人口增长率 5、人口老化(抚养比) 6、各省人口 7、世界人口 四、遇到的问题 遇到的问题 1、数据分页,需要获取从1949-2018年数据,观察到有近20年参数:LAST20,由此推测获取近70年的参数可设置为:LAST70 2、2019年数据没有放上去,可以手动添加上去 3、将数据进行 行列转换 4、列名...
web前端javascript+jquery知识点总结
1.Javascript 语法.用途 javascript 在前端网页中占有非常重要的地位,可以用于验证表单,制作特效等功能,它是一种描述语言,也是一种基于对象(Object)和事件驱动并具有安全性的脚本语言 ...
Python实战:抓肺炎疫情实时数据,画2019-nCoV疫情地图
今天,群里白垩老师问如何用python画武汉肺炎疫情地图。白垩老师是研究海洋生态与地球生物的学者,国家重点实验室成员,于不惑之年学习python,实为我等学习楷模。先前我并没有关注武汉肺炎的具体数据,也没有画过类似的数据分布图。于是就拿了两个小时,专门研究了一下,遂成此文。
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o...
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ...... ...
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!...
渗透测试-灰鸽子远控木马
木马概述 灰鸽子( Huigezi),原本该软件适用于公司和家庭管理,其功能十分强大,不但能监视摄像头、键盘记录、监控桌面、文件操作等。还提供了黑客专用功能,如:伪装系统图标、随意更换启动项名称和表述、随意更换端口、运行后自删除、毫无提示安装等,并采用反弹链接这种缺陷设计,使得使用者拥有最高权限,一经破解即无法控制。最终导致被黑客恶意使用。原作者的灰鸽子被定义为是一款集多种控制方式于一体的木马程序...
Python:爬取疫情每日数据
前言 目前每天各大平台,如腾讯、今日头条都会更新疫情每日数据,他们的数据源都是一样的,主要都是通过各地的卫健委官网通报。 以全国、湖北和上海为例,分别为以下三个网站: 国家卫健委官网:http://www.nhc.gov.cn/xcs/yqtb/list_gzbd.shtml 湖北卫健委官网:http://wjw.hubei.gov.cn/bmdt/ztzl/fkxxgzbdgrfyyq/xxfb...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合...
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名...
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计...
Python新型冠状病毒疫情数据自动爬取+统计+发送报告+数据屏幕(三)发送篇
今天介绍的项目是使用 Itchat 发送统计报告 项目功能设计: 定时爬取疫情数据存入Mysql 进行数据分析制作疫情报告 使用itchat给亲人朋友发送分析报告 基于Django做数据屏幕 使用Tableau做数据分析 来看看最终效果 目前已经完成,预计2月12日前更新 使用 itchat 发送数据统计报告 itchat 是一个基于 web微信的一个框架,但微信官方并不允许使用这...
作为程序员的我,大学四年一直自学,全靠这些实用工具和学习网站!
我本人因为高中沉迷于爱情,导致学业荒废,后来高考,毫无疑问进入了一所普普通通的大学,实在惭愧???? 我又是那么好强,现在学历不行,没办法改变的事情了,所以,进入大学开始,我就下定决心,一定要让自己掌握更多的技能,尤其选择了计算机这个行业,一定要多学习技术。 在进入大学学习不久后,我就认清了一个现实:我这个大学的整体教学质量和学习风气,真的一言难尽,懂的人自然知道怎么回事? 怎么办?我该如何更好的提升自...
粒子群算法求解物流配送路线问题(python)
1.Matlab实现粒子群算法的程序代码:https://www.cnblogs.com/kexinxin/p/9858664.html matlab代码求解函数最优值:https://blog.csdn.net/zyqblog/article/details/80829043 讲解通俗易懂,有数学实例的博文:https://blog.csdn.net/daaikuaichuan/article/...
教你如何编写第一个简单的爬虫
很多人知道爬虫,也很想利用爬虫去爬取自己想要的数据,那么爬虫到底怎么用呢?今天就教大家编写一个简单的爬虫。 下面以爬取笔者的个人博客网站为例获取第一篇文章的标题名称,教大家学会一个简单的爬虫。 第一步:获取页面 #!/usr/bin/python # coding: utf-8 import requests #引入包requests link = "http://www.santostang....
前端JS初级面试题二 (。•ˇ‸ˇ•。)老铁们!快来瞧瞧自己都会了么
1. 传统事件绑定和符合W3C标准的事件绑定有什么区别? 传统事件绑定 &lt;div onclick=""&gt;123&lt;/div&gt; div1.onclick = function(){}; &lt;button onmouseover=""&gt;&lt;/button&gt; 注意: 如果给同一个元素绑定了两次或多次相同类型的事件,那么后面的绑定会覆盖前面的绑定 (不支持DOM事...
相关热词 c# 压缩图片好麻烦 c#计算数组中的平均值 c#获取路由参数 c#日期精确到分钟 c#自定义异常必须继承 c#查表并返回值 c# 动态 表达式树 c# 监控方法耗时 c# listbox c#chart显示滚动条
立即提问