PostgreSQL
 sql >> डेटाबेस >  >> RDS >> PostgreSQL

मैं .net कोर प्रोजेक्ट में सिग्नलआर कोर के साथ पोस्टग्रेस्क्ल डेटाबेस कैसे सुन सकता हूं?

यह उदाहरण काम asp.net core 3.0+ है। पूरा कोड नीचे है।

चरण 1. क्रियाओं को सुनने के लिए PostgreSql पर एक ट्रिगर बनाएं

 create trigger any_after_alarm_speed after
 insert
 or
 delete
 or
 update
 on
 public.alarm_speed for each row execute procedure alarm_speedf();

चरण 2. Postgresql पर प्रक्रिया बनाएं

CREATE OR REPLACE FUNCTION public.alarm_speedf()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF TG_OP = 'INSERT' then
PERFORM pg_notify('notifyalarmspeed', format('INSERT %s %s', NEW.alarm_speed_id, 
NEW.alarm_speed_date));
ELSIF TG_OP = 'UPDATE' then
PERFORM pg_notify('notifyalarmspeed', format('UPDATE %s %s', OLD.alarm_speed_id, 
OLD.alarm_speed_date));
ELSIF TG_OP = 'DELETE' then
PERFORM pg_notify('notifyalarmspeed', format('DELETE %s %s', OLD.alarm_speed_id, 
OLD.alarm_speed_date));
END IF;
RETURN NULL;
END;
$function$;

चरण 3. हब बनाएं

  public class speedalarmhub : Hub
    {

        private IMemoryCache _cache;
       `private IHubContext<speedalarmhub> _hubContext;
         public speedalarmhub(IMemoryCache cache, IHubContext<speedalarmhub> hubContext)
        {
            _cache = cache;
            _hubContext = hubContext; 
        }

        public async Task SendMessage()
        {
            if (!_cache.TryGetValue("SpeedAlarm", out string response))
            {
                SpeedListener speedlist = new SpeedListener(_hubContext,_cache);
                speedlist.ListenForAlarmNotifications();
                string jsonspeedalarm = speedlist.GetAlarmList();
                _cache.Set("SpeedAlarm", jsonspeedalarm);
                await Clients.All.SendAsync("ReceiveMessage", _cache.Get("SpeedAlarm").ToString());
            }
            else
            {
                await Clients.All.SendAsync("ReceiveMessage", _cache.Get("SpeedAlarm").ToString());
            }
        }

    }

चरण 4. श्रोता नियंत्रक बनाएँ

 public class SpeedListener :Controller
{
    private IHubContext<speedalarmhub> _hubContext;
    private IMemoryCache _cache;
    public SpeedListener(IHubContext<speedalarmhub> hubContext,IMemoryCache cache)
    {
        _hubContext = hubContext;
        _cache = cache; 
    }
    static string GetConnectionString()
    {
        var csb = new NpgsqlConnectionStringBuilder
        {
            Host = "yourip",
            Database = "yourdatabase",
            Username = "yourusername",
            Password = "yourpassword",
            Port = 5432,
            KeepAlive = 30
        };
        return csb.ConnectionString;
    }
    public void ListenForAlarmNotifications()
    {
        NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString());
        conn.StateChange += conn_StateChange;
        conn.Open();
        var listenCommand = conn.CreateCommand();
        listenCommand.CommandText = $"listen notifyalarmspeed;";
        listenCommand.ExecuteNonQuery();
        conn.Notification += PostgresNotificationReceived;
        _hubContext.Clients.All.SendAsync(this.GetAlarmList());
        while (true)
        {
            conn.Wait();
        }
    }
    private void PostgresNotificationReceived(object sender, NpgsqlNotificationEventArgs e)
    {

        string actionName = e.Payload.ToString();
        string actionType = "";
        if (actionName.Contains("DELETE"))
        {
            actionType = "Delete";
        }
        if (actionName.Contains("UPDATE"))
        {
            actionType = "Update";
        }
        if (actionName.Contains("INSERT"))
        {
            actionType = "Insert";
        }
        _hubContext.Clients.All.SendAsync("ReceiveMessage", this.GetAlarmList());
    }
    public string GetAlarmList()
    {
        var AlarmList = new List<AlarmSpeedViewModel>();
        using (NpgsqlCommand sqlCmd = new NpgsqlCommand())
        {
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.CommandText = "sp_alarm_speed_process_get";
            NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString());
            conn.Open();
            sqlCmd.Connection = conn;
            using (NpgsqlDataReader reader = sqlCmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    AlarmSpeedViewModel model = new AlarmSpeedViewModel();
                    model.alarm_speed_id = reader.GetInt32(0);
                  // you must fill  your model items
                    AlarmList.Add(model);
                }
                reader.Close();
                conn.Close();
            }



        }
        _cache.Set("SpeedAlarm", SerializeObjectToJson(AlarmList));
        return _cache.Get("SpeedAlarm").ToString();
    }
    public String SerializeObjectToJson(Object alarmspeed)
    {
        try
        {
            var jss = new JavaScriptSerializer();
            return  jss.Serialize(alarmspeed);
        }
        catch (Exception) { return null; }
    }
    private void conn_StateChange(object sender, System.Data.StateChangeEventArgs e)
    {

        _hubContext.Clients.All.SendAsync("Current State: " + e.CurrentState.ToString() + " Original State: " + e.OriginalState.ToString(), "connection state changed");
    }
}

चरण 5 कॉलिंग हब

<script src="~/lib/signalr.js"></script>

<script type="text/javascript">
// Start the connection.
var connection = new signalR.HubConnectionBuilder()
    .withUrl('/speedalarmhub')
    .build();


connection.on('ReceiveMessage', function (message) {

            var encodedMsg = message;
            // Add the message to the page.

});
// Transport fallback functionality is now built into start.
connection.start()
    .then(function () {

        console.log('connection started');
        connection.invoke('SendMessage');
    })
    .catch(error => {
        console.error(error.message);
    });

चरण 6. स्टार्टअप पर नीचे दिए गए कोड कॉन्फ़िगरेशन सेवाएँ जोड़ें

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddSignalR();
        services.AddMemoryCache();
    }

चरण 7. कॉन्फ़िगर विधि में नीचे कोड जोड़ें

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
              endpoints.MapHub<speedalarmhub>("/speedalarmhub");
        });


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. PHP - Postgresql यदि त्रुटि लौटा रहा है तो मैं एक क्वेरी को कैसे रोलबैक कर सकता हूं?

  2. पांडा में इष्टतम खंड आकार पैरामीटर।DataFrame.to_sql

  3. Psql आउटपुट में रैपिंग अक्षम करें

  4. लिक्विबेस + पोस्टग्रेस्क्ल + स्प्रिंग जेपीए:आईडी ऑटो इंक्रीमेंट इश्यू

  5. PostgreSQL में छवियाँ संग्रहीत करना