Web 服务中的 SQL 最佳实践

发布于 2024-08-16 04:58:46 字数 264 浏览 1 评论 0原文

我正在制作一个无状态 Web 服务,它使用 Microsoft SQL Server 读取数据(并且仅读取),而不使用事务。以下哪个是最好的:

  1. 在每次调用 Web 服务时启动 SqlConnection,或者
  2. 将 SqlConnection 存储在静态字段中。

恕我直言,第一种方法会花费太多资源(如果十个客户端向 Web 服务发出十个请求,它会打开一百倍的数据库......),但第二种方法可能有一些问题?也许是比赛条件?还是安全问题?

I'm making a stateless web service which uses Microsoft SQL Server to read data (and only to read), without using transactions. What will be the best of the following:

  1. Starting SqlConnection at each call to the web service, or
  2. Storing SqlConnection in a static field.

IMHO, the first approach will cost too much resources (if ten clients make ten requests to the web service, it opens one hundred times the database...), but the second one has maybe some problems? Maybe race condition? Or security issues?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风启觞 2024-08-23 04:58:46

添加最大/最小池大小允许 SQL Server 池连接,因此即使您创建新的 SqlConnection 对象,数据库也可以为您池连接。

(MSDN,最小池大小)< /a>

例如。 ConnectionString="Catalog=MyDb;MinPoolSize=10;MaxPoolSize=10..."

Adding a max/min pool size allows SQL server to pool connections so even though you create a new SqlConnection object, the db can pool connections for you.

(MSDN, min pool size)

eg. ConnectionString="Catalog=MyDb; MinPoolSize=10; MaxPoolSize=10..."

儭儭莪哋寶赑 2024-08-23 04:58:46

就个人而言,默认情况下,我会在每次调用时打开连接,并依靠连接池来为我解决问题。

Personally, by default I would open the connection with each call, and rely on connection pooling to sort it out for me.

萌辣 2024-08-23 04:58:46

我不会担心连接成本,除非您发现由于某种原因存在问题。连接池将使大部分问题不再那么令人担忧。

如果您大量使用数据库,或者检索大量静态数据,您可能需要考虑实施某种缓存,以减少联系数据库期间的总体成本。即使使用无状态 Web 服务,应用程序缓存中保留的数据越多越好。

I wouldn't worry about the connection cost unless you are finding that to be problematic for some reason. Connection Pooling will make most of this less of a concern.

If you are working heavily with the database, or retrieving a large amount of static data you might want to consider implementing some kind of caching to reduce the overall cost of contacting the database period. The more data you can keep in the application cache the better, even with stateless web services.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文