I have written a tcp server that receives packets from a terminal device. The TCP server interprets the data and saves it in the database using postgres.
The tcp server is multi-threaded. A sample of the code of the moment i open the db connection and save data looks like this;
conn = Sequel.connect('postgres://xxxxx:[email protected]:xxxxx/xxxxxxxxx',:max_connections => 100) # requires pg
transactions = conn.from(:transactions)
if transactions.insert(serial_number: card_serial, balance_before: balance_before, amount: transaction_amount, balance_after: balance_after, transaction_time: time, terminal_number: terminal_number, terminal_type: terminal_type, created_at: Time.now, updated_at: Time.now)
response = {message: "TT01000080", status: "SUCCESS" }
return response
else
response = {message: "", status: "FAILED" }
return response
end
After a few packets, the db creates an error like this; ERROR:PG::ConnectionBad: FATAL: remaining connection slots are reserved for non-replication superuser connections
Even adding the line conn.disconnect
does not help the issue.
The idea to connect to DB every time you want to create a record is not the best approach. Think about changing it to some Connection Pool.
But if you still want to connect every time, try to use the block form of connect, which will assure connection is closed after block finishes.
Also there was no close/disconnect in your code, maybe you put it after return
call (which means it was not executed)
Try something like this:
response = nil
Sequel.connect('postgres://xxxxx:[email protected]:xxxxx/xxxxxxxxx',:max_connections => 100) do |conn| # requires pg
transactions = conn.from(:transactions)
if transactions.insert(serial_number: card_serial, balance_before: balance_before, amount: transaction_amount, balance_after: balance_after, transaction_time: time, terminal_number: terminal_number, terminal_type: terminal_type, created_at: Time.now, updated_at: Time.now)
response = {message: "TT01000080", status: "SUCCESS" }
else
response = {message: "", status: "FAILED" }
end
end
return response
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments