Kill All Active Connections To A Database.

我经常在恢复数据库的时候遇到一个问题,总是有程序自动连接到数据库,导致恢复失败。就算kill掉这些连接,这些程序也很快就重试然后再次连接上来,前后也就几秒的时间(说到这儿就想骂开发的)。

为了解决这个问题,做了一些研究。解决方法有:


1, 尽可能快的kill掉所有的connection然后restore

See Kill All Active Connections To A Database.

The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. The article I linked to uses the following approach which does not have this drawback:

2,或者直接take DB offlline,然后再online。然后抓紧时间restore。

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

3,上面两种方法都是抓紧时间才行。。。如果程序重试的实在太快,就可以take DB to single user mode。 这也是官方推荐的做法。

-- set your current connection to use master otherwise you might get an error

use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
--do you stuff here 
ALTER DATABASE YourDatabase SET MULTI_USER

这种方法的局限是,你取得了数据库的唯一一个链接,然后在query windows里做操作。这意味着你只能使用sql,如果你使用ssms的图形界面来restore,由于背后实际ssms会重新build connection到数据库,所以在单用户模式下是会失败的。这也意味着用第三方工具恢复数据库也是不可能的。不过像Litespeed这种第三方工具一般都会有一个选项,restore的时候可以先自动kill current processes,因此对于这种第三方工具是不需要用单用户模式的。

4,这还有一个更靠谱的方法,但也不是万能的。DBA的命真苦啊。。。

找到程序连接server的login,将该login映射到要恢复的数据库的user删除掉。这样程序就无法自动连接到数据库了。

缺点就是对于具有sysadmin role的用户是无法限制它的权限的。如果临时去掉sysadmin,则该login对其他数据库的操作也会被影响,而我们只希望影响发生在当前我们要restore的数据库。

不过在开发环境下,这么做不会有什么大问题。甚至暂时disable login也是可以的,因为即使disable login,程序正在使用的connection也不会断掉,只是不能建立新的connection。因此该login对其他数据库的使用不会受太大影响。此时就可以赶紧开始restore,一但restore开始,就可以enable login而不必等到restore结束,因为restore已经独占了数据库。

不过在production上还是不敢这么做啊。


不知道还有没有其他的好方法。我搜索了一下,在数据库级别限制访问ip是不可能的。

at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.apache.catalina.startup.Tomcat.start(Tomcat.java:467) ~[tomcat-embed-core-9.0.31.jar!/:9.0.31] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:107) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:88) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:438) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:153) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.2.4.RELEASE.jar!/:5.2.4.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.5.RELEASE.jar!/:2.2.5.RELEASE] at com.cn.travel.TravelApplication.main(TravelApplication.java:16) ~[classes!/:0.0.1-SNAPSHOT] at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na] at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) ~[travel-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) ~[travel-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] at org.springframework.boot.loader.Launcher.launch(Launcher.java:51) ~[travel-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52) ~[travel-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] Caused by: java.lang.IllegalStateException: Not a file URL at org.springframework.boot.loader.jar.Handler.getRootJarFile(Handler.java:304) ~[travel-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT] ... 58 common frames omitted 2025-07-10 04:43:26.009 INFO 26542 --- [ main] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 2025-07-10 04:43:26.012 INFO 26542 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2025-07-10 04:43:26.012 INFO 26542 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1442 ms 2025-07-10 04:43:26.070 INFO 26542 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource 2025-07-10 04:43:26.258 INFO 26542 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited 2025-07-10 04:43:26.368 INFO 26542 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2025-07-10 04:43:26.468 INFO 26542 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final 2025-07-10 04:43:26.607 INFO 26542 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final} 2025-07-10 04:43:26.789 INFO 26542 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MariaDB103Dialect 2025-07-10 04:43:26.819 WARN 26542 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000341: Could not obtain connection metadata : Unknown column 'RESERVED' in 'WHERE' 2025-07-10 04:43:26.819 INFO 26542 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MariaDB103Dialect 2025-07-10 04:43:26.986 INFO 26542 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2025-07-10 04:43:26.990 INFO 26542 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2025-07-10 04:43:27.624 WARN 26542 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning MyBatisConfiguration.pageHelper() 2025-07-10 04:43:27.806 INFO 26542 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2025-07-10 04:43:27.887 INFO 26542 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index 2025-07-10 04:43:27.933 WARN 26542 --- [ main] org.thymeleaf.templatemode.TemplateMode : [THYMELEAF][main] Template Mode 'LEGACYHTML5' is deprecated. Using Template Mode 'HTML' instead. 2025-07-10 04:43:27.958 INFO 26542 --- [ main] t.m.m.autoconfigure.MapperCacheDisabler : Clear tk.mybatis.mapper.util.MsUtil CLASS_CACHE cache. 2025-07-10 04:43:27.959 INFO 26542 --- [ main] t.m.m.autoconfigure.MapperCacheDisabler : Clear tk.mybatis.mapper.genid.GenIdUtil CACHE cache. 2025-07-10 04:43:27.960 INFO 26542 --- [ main] t.m.m.autoconfigure.MapperCacheDisabler : Clear tk.mybatis.mapper.version.VersionUtil CACHE cache. 2025-07-10 04:43:27.960 INFO 26542 --- [ main] t.m.m.autoconfigure.MapperCacheDisabler : Clear EntityHelper entityTableMap cache. 2025-07-10 04:43:28.068 INFO 26542 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2025-07-10 04:43:28.090 INFO 26542 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2025-07-10 04:43:28.092 ERROR 26542 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Web server failed to start. Port 80 was already in use. Action: Identify and stop the process that's listening on port 80 or configure this application to listen on another port. 2025-07-10 04:43:28.094 INFO 26542 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' 2025-07-10 04:43:28.095 INFO 26542 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2025-07-10 04:43:28.096 INFO 26542 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ... 2025-07-10 04:43:28.101 INFO 26542 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed ┌──(kali㉿kali)-[/mnt/hgfs/shiyansucai] └─$ sudo systemctl status mariadb ● mariadb.service - MariaDB 11.8.2 database server Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; preset: disabled) Active: active (running) since Thu 2025-07-10 03:52:33 EDT; 51min ago Invocation: 0e8e759073774f3db4beb277c6a197b5 Docs: man:mariadbd(8) https://mariadb.com/kb/en/library/systemd/ Main PID: 1079 (mariadbd) Status: "Taking your SQL requests now..." Tasks: 11 (limit: 14518) Memory: 161M (peak: 162.7M, swap: 4K, swap peak: 4K) CPU: 2.785s CGroup: /system.slice/mariadb.service └─1079 /usr/sbin/mariadbd Jul 10 03:52:32 kali mariadbd[1079]: 2025-07-10 3:52:32 0 [Note] Plugin 'wsrep-provider' is disabled. Jul 10 03:52:32 kali mariadbd[1079]: 2025-07-10 3:52:32 0 [Note] Recovering after a crash using tc.log Jul 10 03:52:32 kali mariadbd[1079]: 2025-07-10 3:52:32 0 [Note] Starting table crash recovery... Jul 10 03:52:32 kali mariadbd[1079]: 2025-07-10 3:52:32 0 [Note] Crash table recovery finished. Jul 10 03:52:32 kali mariadbd[1079]: 2025-07-10 3:52:32 0 [Note] InnoDB: Buffer pool(s) load completed at 25> Jul 10 03:52:33 kali mariadbd[1079]: 2025-07-10 3:52:33 0 [Note] Server socket created on IP: '127.0.0.1'. Jul 10 03:52:33 kali mariadbd[1079]: 2025-07-10 3:52:33 0 [Note] mariadbd: Event Scheduler: Loaded 0 events Jul 10 03:52:33 kali mariadbd[1079]: 2025-07-10 3:52:33 0 [Note] /usr/sbin/mariadbd: ready for connections. Jul 10 03:52:33 kali mariadbd[1079]: Version: '11.8.2-MariaDB-1 from Debian' socket: '/run/mysqld/mysqld.soc> Jul 10 03:52:33 kali systemd[1]: Started mariadb.service - MariaDB 11.8.2 database server. ┌──(kali㉿kali)-[/mnt/hgfs/shiyansucai] └─$ mysql -u root -p123456 -h 127.0.0.1 travel_db -e "SELECT 1;" +---+ | 1 | +---+ | 1 | +---+ ┌──(kali㉿kali)-[/mnt/hgfs/shiyansucai] └─$ tail -f /mnt/hgfs/shiyansucai/logs/application.log tail: cannot open '/mnt/hgfs/shiyansucai
07-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值