下面是set命令的执行过程,简单分为两个过程,客户端向服务端发送数据,服务端向客户端返回数据,从下面的代码来看:从创建链接到执行命令是没有进行任何并发同步的控制java
public String set(final String key, String value) { checkIsInMulti(); // 执行set命令,实际上是发送set命令和其参数到server端,实际是调用下面的SendCommond(…)方法,发送数据 client.set(key, value); // 等待服务器响应 return client.getStatusCodeReply(); }
public static void sendCommand(final RedisOutputStream os, final Command command, final byte[]... args) { sendCommand(os, command.raw, args); } private static void sendCommand(final RedisOutputStream os, final byte[] command, final byte[]... args) { try { os.write(ASTERISK_BYTE); os.writeIntCrLf(args.length + 1); os.write(DOLLAR_BYTE); os.writeIntCrLf(command.length); os.write(command); os.writeCrLf(); for (final byte[] arg : args) { os.write(DOLLAR_BYTE); os.writeIntCrLf(arg.length); os.write(arg); os.writeCrLf(); } } catch (IOException e) { throw new JedisConnectionException(e); } }
private static Object process(final RedisInputStream is) { final byte b = is.readByte(); if (b == PLUS_BYTE) { return processStatusCodeReply(is); } else if (b == DOLLAR_BYTE) { return processBulkReply(is); } else if (b == ASTERISK_BYTE) { return processMultiBulkReply(is); } else if (b == COLON_BYTE) { return processInteger(is); } else if (b == MINUS_BYTE) { processError(is); return null; } else { throw new JedisConnectionException("Unknown reply: " + (char) b); } }
Jedis客户端支持多线程下并发执行时经过JedisPool实现的,借助于commong-pool2实现线程池,它会为每个请求分配一个Jedis链接,在请求范围内使用完毕后记得归还链接到链接池中,因此在实际运用中,注意不要把一个Jedis实例在多个线程下并发使用,用完后要记得归还到链接池中sql
在一些简单状况下,我是不用DataSource的,通常都会采用单例的方式创建MySQL的链接,刚开始我也不晓得这样写,看别人这样写也就跟着这样写了,忽然有一天我怀疑这样的写发是否可选,一个MySQL的Connection是否在多个线程下并发操做是否安全。安全
在JDK中定义java.sql.Connection只是一个接口,也并无写明它的线程安全问题。查阅资料得知,它的线程安全性由对应的驱动实现:服务器
java.sql.Connection is an interface. So, it all depends on the driver's implementation, but in general you should avoid sharing the same connection between different threads and use connection pools. Also it is also advised to have number of connections in the pool higher than number of worker threads.多线程
这是MySQL的驱动实现,能够看到它在执行时,是采用排它锁来保证链接的在并发环境下的同步。并发
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { // 在使用链接过程当中是采用排它锁的方式 synchronized(this.getConnectionMutex()) { this.checkClosed(); Object pStmt = null; boolean canServerPrepare = true; String nativeSql = this.getProcessEscapeCodesForPrepStmts()?this.nativeSQL(sql):sql; if(this.useServerPreparedStmts && this.getEmulateUnsupportedPstmts()) { canServerPrepare = this.canHandleAsServerPreparedStatement(nativeSql); } ... ...
通常状况下,为了提升并发性,建议使用池技术来解决单连接的局限性,好比经常使用的一些数据源:C3P0等高并发