Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
eshiled-new
/
funasr_web
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit f0ace46f
authored
Mar 21, 2024
by
‘chizw’
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
[+]数据库连接池优化
1 parent
3e2aea69
Show whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
177 additions
and
93 deletions
main.py
mysql_service/funasr_db.py
mysql_service/mysql_pool.py
mysql_service/test_db.py
main.py
View file @
f0ace46
...
@@ -203,7 +203,11 @@ async def create_url(param: UrlParam):
...
@@ -203,7 +203,11 @@ async def create_url(param: UrlParam):
except
Exception
as
e
:
except
Exception
as
e
:
log
.
error
(
f
"error:{e}"
)
log
.
error
(
f
"error:{e}"
)
traceback
.
print_exc
()
traceback
.
print_exc
()
return
{
"error"
:
str
(
e
)}
return
BaseResponse
(
code
=-
1
,
msg
=
"error"
,
data
=
str
(
e
)
)
def
start_kafka
():
def
start_kafka
():
...
...
mysql_service/funasr_db.py
View file @
f0ace46
...
@@ -2,41 +2,52 @@ from mysql_service import MysqlHelper
...
@@ -2,41 +2,52 @@ from mysql_service import MysqlHelper
from
config
import
DbConect
from
config
import
DbConect
from
config.config
import
ConfigInfo
from
config.config
import
ConfigInfo
from
mysql_service
import
mysql_utils
from
mysql_service
import
mysql_utils
from
mysql_service
import
mysql_pool
from
mysql_service.mysql_pool
import
ConnPool
from
mysql_service.mysql_pool
import
MySQLConnectionPool
# db = MysqlHelper.MysqlHelper(
db
=
MysqlHelper
.
MysqlHelper
(
# DbConect.ali_asr_model
DbConect
.
ali_asr_model
# )
config
=
{
"host"
:
ConfigInfo
.
host
,
"port"
:
ConfigInfo
.
port
,
"user"
:
ConfigInfo
.
user
,
"password"
:
ConfigInfo
.
password
,
"database"
:
ConfigInfo
.
database
}
pool
=
ConnPool
(
**
config
)
)
def
insert_ali_asr_model_res
(
task_id
:
str
,
url
:
str
):
def
insert_ali_asr_model_res
(
task_id
:
str
,
url
:
str
):
insert_sql
=
(
insert_sql
=
(
f
"INSERT INTO dj_smartcarlife.ali_asr_model_res (task_id,file_url,task_status) VALUES ('{task_id}','{url}',0
);"
)
"INSERT INTO dj_smartcarlife.ali_asr_model_res (task_id,file_url,task_status) VALUES (
%
s,
%
s,
%
s
);"
)
return
db
.
execute_modify
(
insert_sql
)
return
pool
.
insert_one
(
insert_sql
,
(
task_id
,
url
,
0
,)
)
def
update_ali_asr_model_res
(
task_id
:
str
,
json_output
:
str
,
execute_time
:
int
):
def
update_ali_asr_model_res
(
task_id
:
str
,
json_output
:
str
,
execute_time
:
int
):
update_sql
=
(
update_sql
=
(
f
"update ali_asr_model_res t set t.output_data = '{json_output}',t.task_status = 1, t.execute_time = {execute_time} where t.task_id = '{task_id}'
;"
)
"update ali_asr_model_res t set t.output_data =
%
s,t.task_status = 1, t.execute_time =
%
s where t.task_id =
%
s
;"
)
return
db
.
execute_modify
(
update_sql
)
return
pool
.
update_one
(
update_sql
,
(
json_output
,
execute_time
,
task_id
,)
)
def
update_ali_asr_model_res_fail
(
task_id
:
str
,
exception
:
str
):
def
update_ali_asr_model_res_fail
(
task_id
:
str
,
exception
:
str
):
update_sql
=
(
update_sql
=
(
f
"update ali_asr_model_res t set t.task_status = 2, t.exception_log =
'{exception}' where t.task_id = '{task_id}'
;"
)
f
"update ali_asr_model_res t set t.task_status = 2, t.exception_log =
%
s where t.task_id =
%
s
;"
)
return
db
.
execute_modify
(
update_sql
)
return
pool
.
update_one
(
update_sql
,
(
exception
,
task_id
,)
)
def
select_ali_asr_model_res
(
task_id
:
str
):
def
select_ali_asr_model_res
(
task_id
:
str
):
select_sql
=
(
select_sql
=
(
f
"select id,task_id,file_url,task_status,output_data from ali_asr_model_res aamr where del_flag = 0 and "
f
"select id,task_id,file_url,task_status,output_data from ali_asr_model_res aamr where del_flag = 0 and "
f
"task_id =
'{task_id}'
;"
)
f
"task_id =
%
s
;"
)
return
db
.
execute_select
(
select_sql
)
return
pool
.
select_all
(
select_sql
,
(
task_id
,)
)
def
select_ali_asr_model_wait
():
def
select_ali_asr_model_wait
():
select_sql
=
(
select_sql
=
(
f
"select id,task_id,file_url,task_status,output_data from ali_asr_model_res aamr where aamr.del_flag = 0 and "
f
"select id,task_id,file_url,task_status,output_data from ali_asr_model_res aamr where aamr.del_flag = 0 and "
f
"aamr.output_data is null and aamr.task_status =
0
;"
)
f
"aamr.output_data is null and aamr.task_status =
%
s
;"
)
return
db
.
execute_select
(
select_sql
)
return
pool
.
select_all
(
select_sql
,
0
)
mysql_service/mysql_pool.py
View file @
f0ace46
import
logging
import
json
import
json
import
traceback
import
threading
from
mysql.connector
import
pooling
import
time
import
pymysql
from
DBUtils.PooledDB
import
PooledDB
from
config.config
import
ConfigInfo
from
config.config
import
ConfigInfo
from
log.logger
import
log
from
log.logger
import
log
class
MySQLConnectionPool
:
class
ConnPool
:
def
__init__
(
self
,
pool_name
,
pool_size
,
**
config
):
self
.
pool_name
=
pool_name
self
.
pool_size
=
pool_size
self
.
config
=
config
self
.
cnxpool
=
None
self
.
create_pool
()
def
create_pool
(
self
):
def
__init__
(
self
,
**
config
):
try
:
self
.
pool
=
PooledDB
(
self
.
cnxpool
=
pooling
.
MySQLConnectionPool
(
pool_name
=
self
.
pool_name
,
pool_size
=
self
.
pool_size
,
creator
=
pymysql
,
# 使用链接数据库的模块
**
self
.
config
)
mincached
=
2
,
# 初始化时,链接池中至少创建的链接,0表示不创建
except
Exception
as
e
:
maxconnections
=
32
,
# 连接池允许的最大连接数,0和None表示不限制连接数
log
.
info
(
f
"创建连接池时出错: {e}"
)
blocking
=
True
,
# 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
traceback
.
format_exc
()
host
=
config
[
"host"
],
raise
port
=
config
[
"port"
],
user
=
config
[
"user"
],
def
get_connection
(
self
):
password
=
config
[
"password"
],
if
self
.
cnxpool
is
None
:
database
=
config
[
"database"
]
raise
Exception
(
"连接池尚未创建"
)
)
try
:
return
self
.
cnxpool
.
get_connection
()
except
Exception
as
e
:
log
.
info
(
f
"从连接池获取连接时出错: {e}"
)
traceback
.
format_exc
()
raise
def
close
(
self
):
def
open
(
self
):
if
self
.
cnxpool
:
self
.
conn
=
self
.
pool
.
connection
()
self
.
cnxpool
.
close
()
self
.
cursor
=
self
.
conn
.
cursor
(
cursor
=
pymysql
.
cursors
.
DictCursor
)
# 表示读取的数据为字典类型
return
self
.
conn
,
self
.
cursor
def
close
(
self
,
cursor
,
conn
):
cursor
.
close
()
conn
.
close
()
print
(
"close success"
)
# config = {
def
select_one
(
self
,
sql
,
*
args
):
# "host": ConfigInfo.host,
"""查询单条数据"""
# "user": ConfigInfo.user,
log
.
info
(
f
"execute_select_one sql:{sql}"
%
args
)
# "password": ConfigInfo.password,
conn
,
cursor
=
self
.
open
()
# "database": ConfigInfo.database,
cursor
.
execute
(
sql
,
args
)
# }
result
=
cursor
.
fetchone
()
self
.
close
(
conn
,
cursor
)
log
.
info
(
f
"execute_select_one result:{result}"
)
return
result
config
=
{
def
select_all
(
self
,
sql
,
args
):
"host"
:
'192.168.3.227'
,
"""查询多条数据"""
"port"
:
3306
,
log
.
info
(
f
"execute_select_all sql:{sql}"
%
args
)
"user"
:
'dev_user'
,
conn
,
cursor
=
self
.
open
()
"password"
:
'df234fl'
,
cursor
.
execute
(
sql
,
args
)
"database"
:
'dj_smartcarlife'
result
=
cursor
.
fetchall
()
}
self
.
close
(
conn
,
cursor
)
log
.
info
(
f
"execute_select_all result:{result}"
)
return
result
def
insert_one
(
self
,
sql
,
args
):
"""插入单条数据"""
print
(
sql
)
log
.
info
(
f
"execute_insert_one sql:{sql}"
%
args
)
self
.
execute
(
sql
,
args
,
isNeed
=
True
)
return
True
def
insert_all
(
self
,
sql
,
datas
):
"""插入多条批量插入"""
log
.
info
(
f
"execute_insert_all sql:{sql},args:{datas}"
)
conn
,
cursor
=
self
.
open
()
try
:
cursor
.
executemany
(
sql
,
datas
)
conn
.
commit
()
return
{
'result'
:
True
,
'id'
:
int
(
cursor
.
lastrowid
)}
except
Exception
as
err
:
conn
.
rollback
()
return
{
'result'
:
False
,
'err'
:
err
}
pool
=
MySQLConnectionPool
(
"funasr_pool"
,
1
,
**
config
)
def
update_one
(
self
,
sql
,
args
):
"""更新数据"""
log
.
info
(
f
"execute_update_one sql:{sql}"
%
args
)
self
.
execute
(
sql
,
args
,
isNeed
=
True
)
return
True
def
delete_one
(
self
,
sql
,
*
args
):
"""删除数据"""
log
.
info
(
f
"execute_delete_one sql:{sql}"
%
args
)
self
.
execute
(
sql
,
args
,
isNeed
=
True
)
return
True
def
some_method
():
def
execute
(
self
,
sql
,
args
,
isNeed
=
False
):
"""
执行
:param isNeed 是否需要回滚
"""
conn
,
cursor
=
self
.
open
()
if
isNeed
:
try
:
try
:
# 从连接池中获取连接
cursor
.
execute
(
sql
,
args
)
conn
=
pool
.
get_connection
()
conn
.
commit
()
cursor
=
conn
.
cursor
()
except
:
# 执行SQL查询
cursor
.
execute
(
"select * from ali_asr_model_res aamr;"
)
results
=
cursor
.
fetchall
()
for
row
in
results
:
print
(
row
)
# 提交事务
# conn.commit()
except
Exception
as
e
:
print
(
f
"数据库操作出错: {e}"
)
# 回滚事务
conn
.
rollback
()
conn
.
rollback
()
finally
:
# 关闭游标和连接
if
cursor
:
cursor
.
close
()
if
conn
:
conn
.
close
()
\ No newline at end of file
\ No newline at end of file
else
:
cursor
.
execute
(
sql
,
args
)
conn
.
commit
()
self
.
close
(
conn
,
cursor
)
"""
CREATE TABLE `names` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` VARCHAR(30) DEFAULT NULL COMMENT '姓名',
`sex` VARCHAR(20) DEFAULT NULL COMMENT '性别',
`age` int(5) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='数据导入mysql';
"""
# sql_insert_one = "insert into `names` (`name`, sex, age) values (%s,%s,%s)"
# mysql.insert_one(sql_insert_one, ('唐三', '男', 25))
#
# datas = [
# ('戴沐白', '男', 26),
# ('奥斯卡', '男', 26),
# ('唐三', '男', 25),
# ('小舞', '女', 100000),
# ('马红俊', '男', 23),
# ('宁荣荣', '女', 22),
# ('朱竹清', '女', 21),
# ]
# sql_insert_all = "insert into `names` (`name`, sex, age) values (%s,%s,%s)"
# mysql.insert_all(sql_insert_all, datas)
#
# sql_update_one = "update `names` set age=%s where `name`=%s"
# mysql.update_one(sql_update_one, (28, '唐三'))
#
# sql_delete_one = 'delete from `names` where `name`=%s '
# mysql.delete_one(sql_delete_one, ('唐三',))
#
# sql_select_one = 'select * from `names` where `name`=%s'
# results = mysql.select_one(sql_select_one, ('唐三',))
# print(results)
#
# sql_select_all = 'select * from `names` where `name`=%s'
# results = mysql.select_all(sql_select_all, ('唐三',))
# print(results)
def
test_sql
():
mysql
=
ConnPool
()
sql_select_all
=
'select id,task_id,file_url,task_status,output_data from `ali_asr_model_res` where `task_id`=
%
s'
results
=
mysql
.
select_all
(
sql_select_all
,
(
'0bfa2d5c-e662-11ee-8b56-b083fec01e48'
,))
print
(
results
[
0
][
"task_id"
])
json_res
=
json
.
dumps
(
results
,
ensure_ascii
=
False
)
print
(
json_res
)
mysql_service/test_db.py
View file @
f0ace46
import
time
import
time
import
traceback
import
traceback
from
mysql_service
import
mysql_pool
from
mysql.connector
import
pooling
from
mysql.connector
import
pooling
from
log.logger
import
log
from
log.logger
import
log
from
mysql_service
import
funasr_db
from
mysql_service
import
funasr_db
from
mysql_service
import
MysqlHelper
from
mysql_service
import
MysqlHelper
from
config
import
DbConect
from
config
import
DbConect
from
mysql_service
import
mysql_utils
from
mysql_service
import
mysql_utils
from
mysql_service.mysql_pool
import
MySQLConnectio
nPool
from
mysql_service.mysql_pool
import
Con
nPool
from
config.config
import
ConfigInfo
from
config.config
import
ConfigInfo
consuming_start_time
=
time
.
perf_counter
()
consuming_start_time
=
time
.
perf_counter
()
# db = MysqlHelper.MysqlHelper(
# db = MysqlHelper.MysqlHelper(
...
@@ -29,9 +27,14 @@ sql = "INSERT INTO dj_smartcarlife.ali_asr_model_res (task_id,file_url,task_stat
...
@@ -29,9 +27,14 @@ sql = "INSERT INTO dj_smartcarlife.ali_asr_model_res (task_id,file_url,task_stat
# select_res = mysql_utils.execute_sql("select * from ali_asr_model_res aamr;")
# select_res = mysql_utils.execute_sql("select * from ali_asr_model_res aamr;")
# print(select_res)
# print(select_res)
for
i
in
range
(
1
):
for
i
in
range
(
1
):
# res = mysql_pool.some_method()
res1
=
funasr_db
.
insert_ali_asr_model_res
(
task_id
,
url
)
res
=
funasr_db
.
select_ali_asr_model_wait
()
print
(
"res1:
%
s"
%
res1
)
print
(
res
)
res2
=
funasr_db
.
update_ali_asr_model_res
(
task_id
,
sql
,
int
(
time
.
time
()))
print
(
"res2:
%
s"
%
res2
)
res3
=
funasr_db
.
select_ali_asr_model_res
(
task_id
)
print
(
"res3:
%
s"
%
res3
)
res4
=
funasr_db
.
select_ali_asr_model_wait
()
print
(
"res4:
%
s"
%
res4
)
try
:
try
:
# time.sleep(2)
# time.sleep(2)
execute_time
=
time
.
perf_counter
()
-
consuming_start_time
execute_time
=
time
.
perf_counter
()
-
consuming_start_time
...
@@ -111,9 +114,3 @@ import json
...
@@ -111,9 +114,3 @@ import json
# res = execute_sql(SQL)
# res = execute_sql(SQL)
# print(res)
# print(res)
#
#
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment