在会话变量中存储数据库连接 [英] Storing database connection in a session variable

查看:84
本文介绍了在会话变量中存储数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在php中的会话中无法通过mysqli连接


我们中的许多人都编写了需要数据库的PHP应用程序;主要是MySQL,但我经常使用非常小的MS Access数据库为技术能力较差的人,所以他们可以下载一个调整他们/保存备份等。 (不管这是否正确,我不知道)。



我注意到,是很多时间花在连接和运行一些查询。因为这个我有一个有趣的想法:存储连接和可能的结果集,在 $ _ SESSION 变量中大部分是静态的,以减少用户导航网站的负担。 / p>

显然这样做需要很多考虑。当会话被销毁时关闭连接只是一个开始。



我的问题归结为:这是真的可能吗?如果是,我应该注意什么(除了会话固定,因为它是自己的问题适用于所有会话)?

解决方案

即使你能做到这一点馊主意。你会结束许多并发打开的连接,这将打破你的最大连接非常快...特别是如果其生命周期扩展超过sub 100ms(取决于你的查询)到20分钟或更长。有了开放的连接,像MySQL这样的东西也不能正确地重置它的内存分配,整个系统都去了地狱。总之,这不是DB,除非你的代码的唯一消费者将是一个单一的用户。



另外,我强烈推荐缓存技术专门用于减少数据库负载和避免连接时间。使用类似的,最简单的,memcached将大大提高性能,你将能够指定确切的多少系统资源进入缓存 - 同时让数据库在需要时获取数据的工作到。


Possible Duplicate:
Can't pass mysqli connection in session in php

Many of us have written PHP applications that require databases; mostly MySQL, but I have often used very small MS Access databases for people less technically capable so they can download an tweak them/save backups/etc. on their own (whether this is correct or not, I have no idea).

What I notice, is a lot of time is spent connecting and running some of the same queries. Because of this I had an interesting thought: Storing the connection and possible result sets that are mostly static in a $_SESSION variable to reduce the burden as the user navigates the site.

Obviously doing so requires a lot of consideration. Things like closing the connection when the session is destroyed is just the start.

My question boils down to: Is this really something possible? And if so, what things should I be aware of (besides session fixation, as it is its own problem that applies to all sessions)?

解决方案

Even if you could do this (resource vs. data), this is a bad idea. You'll wind up with lots of concurrent open connections, which will blow your max connections very quickly... especially if its lifecycle is expanded beyond sub 100ms (depending on your queries) to 20 minutes or more. With open connections, something like MySQL also won't be able to reset its memory allocations properly, and the whole system sort of goes to hell. In short, this is not what DBs are for unless the only consumer of your code will be a single user.

As an alternative, I'd highly recommend caching technologies which are designed specifically to reduce database load and obviate connection times. Using something like, at its simplest, memcached will dramatically improve performance all the way around, and you'll be able to specify exactly how many system resources go into the cache -- while letting the database do its job of getting data when it needs to.

这篇关于在会话变量中存储数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆