Jedis 与 MySQL的连接线程安全问题

Jedis的连接是非线程安全的

下面是set命令的执行过程,简单分为两个过程,客户端向服务端发送数据,服务端向客户端返回数据,从下面的代码来看:从建立连接到执行命令是没有进行任何并发同步的控制

public String set(final String key, String value) {
  checkIsInMulti();
  // 执行set命令,其实是发送set命令和其参数到server端,实际是调用下面的SendCommond(…)方法,发送数据
  client.set(key, value);
  // 等待服务器响应
  return client.getStatusCodeReply();
}

set 命令的数据发送过程

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);
  }
}

set命令接收服务端响应过程

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);
  }
}

JedisPool是线程安全的

Jedis客户端支持多线程下并发执行时通过JedisPool实现的,借助于commong-pool2实现线程池,它会为每一个请求分配一个Jedis连接,在请求范围内使用完毕后记得归还连接到连接池中,所以在实际运用中,注意不要把一个Jedis实例在多个线程下并发使用,用完后要记得归还到连接池中

MySQL的连接是线程安全的

在一些简单情况下,我是不用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等

posted @ 2018-04-17 20:30  梁天  阅读(330)  评论(0编辑  收藏  举报