Java实现pgsql异步通知

1.创建触发器执行函数

create or replace function _table_update_notify_() returns trigger as $$
begin
    perform _pg_notify_('table_update',json_build_object('table',TG_TABLE_NAME,'timestamp',current_timestamp)::text);
    return new;
end;
$$ language plpgsql;

函数被调用会执行pg_notify()方法 实现异步通知

2.创建触发器

drop trigger if exists n_user_u on test.demo."user";
create trigger n_user_u after insert or update or delete on test.demo."user"
> for each statement execute procedure _table_update_notify_();

对应的数据表有 insert or update or delete 操作就会触发触发器,触发器调用上一步创建的方法

3.新建SpringBoot项目

新建SpringBoot项目,
Java中LISTEN / NOTIFY的JDBC驱动程序不支持真正的事件驱动通知。你必须经常轮询数据库以查看是否有新的通知。
所以jdbc选用pgsql-ng,支持异步通知
pgsql-ng文档地址 http://impossibl.github.io/pgjdbc-ng/

引入依赖


<dependency>
<groupId>com.impossibl.pgjdbc-ng</groupId>
<artifactId>pgjdbc-ng</artifactId>
<version>0.8.2</version>
</dependency>

编写监听器

_@Configuration
public class Pglistener _{
_    _@Autowired
    DataSource dataSource;
    @Bean
    public void pgListen_() _throws SQLException _{
_        _System._out_.println_(_"初始化监听器"_)_;
        _//获取数据库连接
        _Connection connection = dataSource.getConnection_()_;
        _//将数据库连接还原为原始的PGConnection
        _PGConnection pgConnection = connection.unwrap_(_PGConnection.class_)_;
        _//为连接添加监听器
        _pgConnection.addNotificationListener_(_new PGNotificationListener_() {
            _@Override
            public void notification_(_int processId, String channelName, String payload_) {
_                _System._out_.println_(_"Received Notification: " + processId + ", " + channelName + ", " + payload_)_;
            _}
_            _@Override
            public void closed_() {
                _PGNotificationListener.super.closed_()_;
            _}
        })_;
        _//设置监听通道 对应pg_notify的channel
        _Statement stmt = pgConnection.createStatement_()_;
        System._out_.println_(_"LISTEN table_update"_)_;
        stmt.executeUpdate_(_"LISTEN table_update"_)_;


    _}
}_

_
此时修改监听的表,程序会收到pgsql的异步通知,打印日志_

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值