简体   繁体   English

如何为 postgres 连接设置 application_name?

[英]How to set application_name for postgres connections?

I'm using tomcat connection pool org.apache.tomcat.jdbc.pool.DataSource .我正在使用 tomcat 连接池org.apache.tomcat.jdbc.pool.DataSource The connections appear in my database pg_stat_activity with empty application_name .连接出现在我的数据库pg_stat_activity中,且application_name为空。

How could I set that application name in my java app, so I know where each connection comes from (as there will be multiple applications accessing the same db)?如何在我的 java 应用程序中设置该应用程序名称,以便我知道每个连接来自哪里(因为将有多个应用程序访问同一个数据库)?

You could specify the application name in the connection string.您可以在连接字符串中指定应用程序名称。
Documentation here .文档在这里

Example:例子:

jdbc:postgresql://localhost:5435/DBNAME?ApplicationName=MyApp

Take care : the param names are case sensitive.注意:参数名称区分大小写。

使用设置命令:

set application_name to my_application;

You can add this to the JDBC URL that you use in your connection pool definition:您可以将其添加到您在连接池定义中使用的 JDBC URL:

jdbc:postgresql://localhost/postgres?ApplicationName=my_app

If you want to change it dynamically eg to reflect different modules inside your application, the you can use the SET command as shown by klin.如果您想动态更改它,例如反映应用程序的不同模块,您可以使用 klin 所示的SET命令。

If you want to set programmatically, the PostgreSQL drivers also have a method you can call:如果您想以编程方式设置,PostgreSQL 驱动程序也有一个您可以调用的方法:

PGPoolingDataSource ds = new PGPoolingDataSource();
ds.setApplicationName(applicationName);

对于那些使用普通连接字符串而不是 jdbc 的人:

postgresql://other@localhost/otherdb?application_name=myapp

If you're using Python library psycopg2 , here's how you can do如果您使用的是 Python 库psycopg2 ,那么您可以这样做

import psycopg2    
psycopg2.connect(host=host_ip, database=db_name, user=user, password=db_pwd, application_name="Python Local Test Script")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM