PostgreSQL的notify 与listen (五)

磨砺技术珠矶,践行数据之道,追求卓越价值 

回到上一级页面: PostgreSQL基础知识与基本操作索引页     回到顶级页面:PostgreSQL索引页

 

利用PostgreSQL的notify /listen 机制,可以实现在psql客户端看到通知消息。
但是,如果是Java 应用程序,将会是怎样的?

按照PostgreSQL的官方文档,是这样说的:

http://jdbc.postgresql.org/documentation/91/listennotify.html

A key limitation of the JDBC driver is that it cannot receive asynchronous notifications and must poll the backend to check if any notifications were issued.

Java程序通过JDBC Driver,来被数据库端数据变化/消息通知激活,是不能直接实现的。
只不过是采用变通方式,还是要轮询数据库端,只是"select 1"这种查询,可以尽量使网络通讯量较少。

摘要其关键代码如下:

 1 while (true) {                
 2     try {            
 3       // issue a dummy query to contact the backend        
 4       // and receive any pending notifications.        
 5       Statement stmt = conn.createStatement();        
 6       ResultSet rs = stmt.executeQuery("SELECT 1");        
 7       rs.close();        
 8       stmt.close();        
 9                 
10      org.postgresql.PGNotification notifications[] = pgconn.getNotifications(); 11      if (notifications != null) {        
12          for (int i=0; i<notifications.length; i++) {    
13           System.out.println("Got notification: " + notifications[i].getName());
14             }    
15      }        
16                 
17      // wait a while before checking again for new        
18      // notifications        
19      Thread.sleep(500);
...

打个比方来说,剧场看门人和剧场经理是观察者模式,剧场经理有了新剧目,他会通知看门人。

而你作为观众,没必要老去打扰繁忙的剧场经理,只要隔一段时间打电话给剧场看门人。

电话费比较贵(越洋国际电话10美刀/分钟)所以,你给看门人打电话时,只是简单问候。
如果剧场看门人已经被剧场经理通知有新剧目,他会告诉你说有新戏某某!你就知道有新剧目了。

你作为观众就是 Java Thread      
电话设备和电话线就是 JDBC Driver
你给看门人打电话就是 "select 1"  
看门人就是 libpq里的 PGNotification
剧场经理就是 PostgreSQL后台服务器进程

你的大老板则是最终用户。大老板看来,下面的经理(Java Application)忙着向他汇报工作;

当国外剧场有新剧目的时候,花很少钱(你和看门人联系,废话从不多讲),也没有耽误(电话都是你这个Java Thread 来用的) 工作,就知道了消息;于是大老板坐飞机去悉尼看戏去也。

 

磨砺技术珠矶,践行数据之道,追求卓越价值 

回到上一级页面: PostgreSQL基础知识与基本操作索引页     回到顶级页面:PostgreSQL索引页

posted @ 2012-07-12 16:36  健哥的数据花园  阅读(2008)  评论(0编辑  收藏  举报