连接数据库(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;
6. public class Test {
7. public static void main(String[] args) {
8. String driver = "org.postgresql.Driver";
9. Connection conn;
10. try {
11. Class.forName(driver).newInstance();
12. Properties properties = new Properties();
13. properties.setProperty("user", "username");
14. properties.setProperty("password", "password");
15. conn = DriverManager.getConnection("jdbc:postgresql://localhost:8000/postgres?socketFactory=org.newsclub" +
16. ".net.unix" +
17. ".AFUNIXSocketFactory$FactoryArg&socketFactoryArg=/data/tmp/.s.PGSQL.8000",
18. properties);
19. System.out.println("Connection Successful!");
20. Statement statement = conn.createStatement();
21. statement.executeQuery("select 1");
22. } catch (Exception e) {
23. e.printStackTrace();
24. }
25. }
26. }
须知:
- socketFactoryArg参数配置根据真实路径进行配置,与GUC参数unix_socket_directory的值保持一致。
- 连接主机名必须设置为“localhost”。
须知: