连接数据库(UDS方式)

Unix domain socket用于同一主机上不同进程间的数据交换,通过添加junixsocket获取套接字工厂使用。

需要引用的jar包有junixsocket-core-XXX.jar、junixsocket-common-XXX.jar、junixsocket-native-common-XXX.jar。同时需要在URL连接串中添加:socketFactory=org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg&socketFactoryArg=[path-to-the-unix-socket]

示例:

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.Statement;
  4. import java.util.Properties;
  5. public class Test {
  6. public static void main(String[] args) {
  7. String driver = "org.postgresql.Driver";
  8. Connection conn;
  9. try {
  10. Class.forName(driver).newInstance();
  11. Properties properties = new Properties();
  12. properties.setProperty("user", "username");
  13. properties.setProperty("password", "password");
  14. conn = DriverManager.getConnection("jdbc:postgresql://localhost:8000/postgres?socketFactory=org.newsclub" +
  15. ".net.unix" +
  16. ".AFUNIXSocketFactory$FactoryArg&socketFactoryArg=/data/tmp/.s.PGSQL.8000",
  17. properties);
  18. System.out.println("Connection Successful!");
  19. Statement statement = conn.createStatement();
  20. statement.executeQuery("select 1");
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. }

连接数据库(UDS方式) - 图1 须知:

  • socketFactoryArg参数配置根据真实路径进行配置,与GUC参数unix_socket_directory的值保持一致。
  • 连接主机名必须设置为“localhost”。