ASP.NET HttpModule 中的线程安全缓存
下面是我有一个 ASP.NET 4.0 应用程序的场景
,其中有很多旧版 URL 重写。我想构建一个 HTTP 模块,该模块将查看这些重写的数据库,并在需要时执行 301 重定向。该表中有数万条记录。
显然,我需要进行某种缓存,这样我就不会访问数据库并搜索每个页面请求的所有这些记录。
我们的要求之一是当我们的应用程序由于某种原因(工作进程回收或其他原因)回收时具有快速的启动时间。所以我不想在应用程序启动时加载整个表。应用程序的启动速度已经非常慢了。
我的绝妙/可笑的想法是,
- 在我的 HttpModule 中的应用程序启动时创建一个空字典来保存重写。
- 启动后台工作线程。该应用程序继续启动。
- 后台工作线程会更新字典,比如,哦,最常用的 1000 个重写。
问题
我的问题是:
- 这很荒谬吗?
- 有没有这样的事情 线程安全的字典?这 后台线程可能正在更新 当新请求时字典 正在进来。
- 所有的锁都可以吗? 在线程安全中进行 收集会减慢传入请求吗?
谢谢!!
Here's the scenario
I have an ASP.NET 4.0 application which has a LOT of legacy URL rewrites. I want to build an HTTP module that will look at a database of these rewrites and do a 301 redirect if needed. There's tens of thousands of records in this table.
So obviously I need to do some sort of caching so I'm not hitting the database and searching through all those records for each page request.
One of our requirements is to have a fast start up time when our application recycles for some reason (worker process recycles or what have you). So I don't want to load the whole table at app start up. The app start up is already excruciatingly slow.
My brilliant/ridiculous idea is to,
- At app start up in my HttpModule create an empty dictionary to hold rewrites.
- Start a background worker thread. The app continues starting up.
- The background worker thread updates the dictionary with say, oh, the most 1000 most used rewrites.
Questions
My questions are:
- Is this ridiculous?
- Is there such a thing as
a thread-safe dictionary? The
background thread might be updating
the dictionary while new requests
are coming in. - Would all the locking
that goes on in a thread-safe
collection slow down incoming requests?
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的目标是 .NET 4.0,则可以使用
ConcurrentDictionary
它会为您处理并发方面的所有问题。只需使用GetOrAdd
处理传入请求,使用AddOrUpdate
处理您的背景填充想法。我也想提出一些问题供您思考。如果您有这数千个 URL,您真的只在一台服务器上运行吗?我这么问是因为您在这里只讨论本地缓存方案。如果您有三台服务器,它们都将在数据库中获取 URL 数据。您是否正在研究 Windows Server AppFabric 或 Memcached 等分布式缓存技术?
If you're targeting .NET 4.0, you can use
ConcurrentDictionary
and it will take care of all the magic for you in terms of concurrency. Just use theGetOrAdd
for incoming requests andAddOrUpdate
for your background population idea.I would also like to pose something for you to think about as well. If you've got these thousands of URLs are you really only running on one server? I ask that because you're only talking about a local caching scheme here. If you have three servers all of them are going to be pounding the DB for the URL data. Are you looking into a distributed caching technology like Windows Server AppFabric or Memcached?