본문 바로가기
호구지책/C/C++/C#

[C#] postgreSQL Notification 사용하기

by 하늘의흐름 2017. 6. 6.
반응형

C#에서 postgreSQL의 Notification(알림;노티피케이션)을 사용하는 방법을 알아보겠다.

Notification은 스마트폰의 push와 비슷하다고 볼 수 있다.

다만 스마트폰처럼 상단에 수신되었다고 알려주는 것은 없고,

별도로 이벤트를 만들어서 해당 메시지를 확인하고,

필요한 작업을 해줘야 한다.


Npgsql 라이브러리(C#)를 사용하면 

응용프로그램에서 손 쉽게 DB를 호출하여

조작할 수 있다.


SyncNotification이라고 알림이 사용가능한 상태인지 알려주는 bool 값이 있다.

이게 true일 때만 Notification을 수신할 수 있다.


SyncNotificaiotn을 활성화하려면 

DB를 연결할 때, 뒤에 옵션 값으로 추가해줘야 한다.


DB 연결 스트링 (C#)

conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;" + 
"Password=my_password;Database=helper_db.psql;SyncNotification=true");


연결스트링에 위처럼 옵션을 추가하고

conn.SyncNotification 값을 확인하면

true로 리턴되는 걸 알 수 있다.



알림의 구체적인 사용법 (C#)


//DB 알림 수신 준비 : 수신할 알림의 이름을 입력한다.
string sql = "listen mynotify";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.ExecuteNonQuery();

//DB 알림 이벤트 연결 
conn.Notification += OnNotification;

//postgreSQL Notification 이벤트 수신 : 이벤트 수신시 필요한 작업을 처리한다.
        public void OnNotification(object sender, NpgsqlNotificationEventArgs e)
{ 

    if (Application.Current.Dispatcher.CheckAccess())
    {
	
    }
    else
    {
	if (e.AdditionalInformation == "msg1")
	{ 
	    Console.WriteLine("event handled : " + e.AdditionalInformation);
	}
	else if (e.AdditionalInformation == "msg2")
	{
	    
	    Console.WriteLine("event handled : " + e.AdditionalInformation);
	}  
	else {

	    Console.WriteLine("event handled: " + e.AdditionalInformation);
	}
    }
}




알림의 전달 (postgreSQL)

PgAdmin 등에서 다음의 쿼리로 테스트한다.

notify mynotify, 'msg1';


모든 설정을 제대로 잡았다면

출력로그에 

event handled : msg1

라고 출력된다.



참고

NOTIFY - postgreSQL 공식 사이트

31.8. Asynchronous Notification

Npgsql - Notify

Can't immediately receive multiple notifications in Npgsql



반응형

댓글