仅用于设置 cookie 的服务器

发布于 2024-11-03 14:58:30 字数 392 浏览 0 评论 0原文

在工作中,我们遇到了设置服务器端 cookie 的问题——很多。现在我们有一个 PHP 脚本,其唯一目的是在客户端上为我们的域设置 cookie。这种情况比对服务器(正在运行应用程序)的“正常”请求发生的次数要多得多,因此我们讨论了将其移动到自己的服务器。这将是一台 Apache 服务器,可能是专用的,有一个 3 行长的 PHP 脚本,只是一遍又一遍地运行。

当然,必须有一种更快、更好的方法来做到这一点,而不是启动整个 PHP 环境。基本上,我需要一些超级简单的东西,可以整天/晚上做以下事情:

  1. 检查是否设置了某个 cookie,
  2. 如果未设置该 cookie,则用随机散列填充它(现在它是一个简单的 md5(microtime))

有什么建议吗?

At work we ran up against the problem of setting server-side cookies - a lot of them. Right now we have a PHP script, the sole purpose of which is to set a cookie on the client for our domain. This happens a lot more than 'normal' requests to the server (which is running an app), so we've discussed moving it to its own server. This would be an Apache server, probably dedicated, with one PHP script 3 lines long, just running over and over again.

Surely there must be a faster, better way of doing this, rather than starting up the whole PHP environment. Basically, I need something super simple that can sit around all day/night doing the following:

  1. Check if a certain cookie is set, and
  2. If that cookie is not set, fill it with a random hash (right now it's a simple md5(microtime))

Any suggestions?

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

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

发布评论

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

评论(4

街道布景 2024-11-10 14:58:30

可以自己创建一个简单的http服务器来接受请求并返回set-cookie标头和空正文。这将允许您将 cookie 生成开销移至您认为合适的任何地方。

不过,我同意上面的观点;除非 cookie 生成非常昂贵,否则我认为从当前设置转移不会获得太多好处。

举例来说,这是一个使用 Tornado 编写的极其简单的服务器,它只需设置一个GET 或 HEAD 请求上的 cookie 到“/”。它包括一个侦听“/async”的异步示例,该示例可能有用,具体取决于您获取 cookie 值的操作。

import time
import tornado.ioloop
import tornado.web


class CookieHandler(tornado.web.RequestHandler):
    def get(self):
        cookie_value = str( time.time() )
        self.set_cookie('a_nice_cookie', cookie_value, expires_days=10)
        # self.set_secure_cookie('a_double_choc_cookie', cookie_value)
        self.finish()

    def head(self):
        return self.get()


class AsyncCookieHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self._calculate_cookie_value(self._on_create_cookie)

    @tornado.web.asynchronous
    def head(self):
        self._calculate_cookie_value(self._on_create_cookie)

    def _on_create_cookie(self, cookie_value):
        self.set_cookie('double_choc_cookie', cookie_value, expires_days=10)
        self.finish()

    def _calculate_cookie_value(self, callback):
        ## meaningless async example... just wastes 2 seconds
        def _fake_expensive_op():
            val = str(time.time())
            callback(val)
        tornado.ioloop.IOLoop.instance().add_timeout(time.time()+2, _fake_expensive_op)



application = tornado.web.Application([
    (r"/", CookieHandler),
    (r"/async", AsyncCookieHandler),
])


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

使用 Supervisord 启动此流程,您将拥有一个简单、快速、低开销的服务器曲奇饼。

You could create a simple http server yourself to accept requests and return the set-cookie header and empty body. This would allow you to move the cookie generation overhead to wherever you see fit.

I echo the sentiments above though; Unless cookie generation is significantly expensive, I don't think you will gain much by moving from your current setup.

By way of an example, here is an extremely simple server written with Tornado that simply sets a cookie on GET or HEAD requests to '/'. It includes an async example listening for '/async' which may be of use depending on what you are doing to get your cookie value.

import time
import tornado.ioloop
import tornado.web


class CookieHandler(tornado.web.RequestHandler):
    def get(self):
        cookie_value = str( time.time() )
        self.set_cookie('a_nice_cookie', cookie_value, expires_days=10)
        # self.set_secure_cookie('a_double_choc_cookie', cookie_value)
        self.finish()

    def head(self):
        return self.get()


class AsyncCookieHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self._calculate_cookie_value(self._on_create_cookie)

    @tornado.web.asynchronous
    def head(self):
        self._calculate_cookie_value(self._on_create_cookie)

    def _on_create_cookie(self, cookie_value):
        self.set_cookie('double_choc_cookie', cookie_value, expires_days=10)
        self.finish()

    def _calculate_cookie_value(self, callback):
        ## meaningless async example... just wastes 2 seconds
        def _fake_expensive_op():
            val = str(time.time())
            callback(val)
        tornado.ioloop.IOLoop.instance().add_timeout(time.time()+2, _fake_expensive_op)



application = tornado.web.Application([
    (r"/", CookieHandler),
    (r"/async", AsyncCookieHandler),
])


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Launch this process with Supervisord and you'll have a simple, fast, low-overhead server that sets cookies.

千年*琉璃梦 2024-11-10 14:58:30

可以尝试使用mod_headers(通常默认安装中可用)手动构建 Set-Cookie 标头并发出它 - 无需编程只要每次都是相同的 cookie。类似这样的东西可以在 .htaccess 文件中工作:

Header add Set-Cookie "foo=bar; Path=/; Domain=.foo.com; Expires=Sun, 06 May 2012 00:00:00 GMT"

但是,这对您不起作用。这里没有代码。这只是一个愚蠢的标题。它无法提供您想要的新随机值,也无法按照标准做法调整到期日期。

这将是一个 Apache 服务器,可能是专用的,有一个 3 行长的 PHP 脚本,只是一遍又一遍地运行。 [...] 当然必须有一种更快、更好的方法来做到这一点,而不是启动整个 PHP 环境。

您是否使用 APC 或其他字节码缓存?如果是这样,几乎没有启动成本。因为您正在谈论为此设置整个服务器,所以听起来您也可以控制服务器。这意味着您可以关闭 apc。 stat 甚至更少的启动命中。

实际上,如果该脚本所做的只是构建 md5 哈希值并设置 cookie,那么它应该已经非常快了,特别是如果它是 mod_php。通过基准测试和测试,您是否已经知道该脚本的性能没有达到您的预期?如果是这样,您能与我们分享这些基准吗?

You could try using mod_headers (usually available in the default install) to manually construct a Set-Cookie header and emit it -- no programming needed as long as it's the same cookie every time. Something like this could work in an .htaccess file:

Header add Set-Cookie "foo=bar; Path=/; Domain=.foo.com; Expires=Sun, 06 May 2012 00:00:00 GMT"

However, this won't work for you. There's no code here. It's just a stupid header. It can't come up with the new random value you'd want, and it can't adjust the expire date as is standard practice.

This would be an Apache server, probably dedicated, with one PHP script 3 lines long, just running over and over again. [...] Surely there must be a faster, better way of doing this, rather than starting up the whole PHP environment.

Are you using APC or another bytecode cache? If so, there's almost no startup cost. Because you're talking about setting up an entire server just for this, it sounds like you control the server as well. This means that you can turn off apc.stat for even less of a startup hit.

Really though, if all that script is doing is building an md5 hash and setting a cookie, it should already be blisteringly fast, especially if it's mod_php. Do you already know, though benchmarking and testing, that the script isn't performing as well as you'd like? If so, can you share those benchmarks with us?

凯凯我们等你回来 2024-11-10 14:58:30

知道为什么你认为你需要额外的服务器会很有趣 - 你真的有生成 cookie 或其他地方的瓶颈吗?是因为请求大量发生而写入日志吗?阿贾克斯轮询?客户端下载速度?

至少对于初学者来说,我会寻找比获取时间来生成“随机哈希”更有效的方法。例如,在我拥有的这台英特尔 i7 笔记本电脑上,从 microtime 生成 999999 md5 哈希值大约需要 4 秒,而使用随机数执行相同的操作则要快一秒(不考虑 rand 的播种)。

然后,如果您考虑打开/和关闭套接字,只需移动您的脚本(这很可能已经非常快 - 也就是说,不知道您的页面如何考虑到这一点),您最终将实际上减慢请求。实际上,现在我重新阅读了你的问题,这让我觉得你的 cookie setter 脚本已经是一个专用页面了?或者您只是“包含”到另一个 php 脚本提供的真实内容中?如果没有,请尝试该方法。另外,如果您有 apache 的默认日志记录规则,如果在自己的页面上设置 cookie,您的 apache 将为此记录一行,并且在高负载系统中,这将累积到 apache 花费的总 io 时间。

另外,考虑一下测试 cookie 是否已设置然后设置它,可能比仅仅强制设置它慢,即使 cookie 存在或不存在?

但总的来说,我认为你不需要设置一个服务器来卸载 cookie 生成,而不了解更多关于现在如何处理 cookie 的信息。除非你正在做一些非常讨厌的事情。

It would be interesting to know why do you think you need extra server - do you actually have a bottle neck for generating the cookie or somewhere else ? Is it the log writing as requests happen alot ? ajax polling ? Client download speed ?

Atleast for starters, i'd look something more efficient than fetching time to generate the "random hash". For example, on this intel i7 laptop i have, generating 999999 md5 hashes from microtime takes roughly about 4 seconds and doing same thing with random numbers is second faster (not taking a seeding of rand into account).

Then, if you take opening/and closing of socket into account, just moving your script (which is most likely already really fast - that is, without knowing how your pages take that into account), you will end up actually slowing down the requests. Actually, now that i've re-read your question, it makes me think that your cookie setter script is already a dedicated page ? Or do you just "include" into real content served by another php script? If not, try that approach. Also this would beneficial if you have default logging rules for apache, if cookies are set in on own page, your apache will log a row for that and in high load systems, this will cumulate to total io time spend by apache.

Also, consider that testing if cookie is set and then setting it, might be slower than just to forcefully set it always even if cookie exists or not ?

But overall, i don't think you'd need to set up a server just to offload cookie generation without knowing more about how you handle the cookies now.. Unless you are doing something really nasty.

遥远的绿洲 2024-11-10 14:58:30

Apache 有一个名为 mod_usertrack 的模块,它看起来可能完全按照您的操作想。不需要 PHP,您可以创建一个真正优化的轻量级 Apache 配置来为此提供服务。

如果你想要更快的东西并且很高兴不使用 Apache,你可以使用 lighttpd,它是 mod_usertrack 或 nginx 的 HttpUserId 模块

Apache has a module called mod_usertrack which looks like it might do exactly what you want. There's no need for PHP and you could likely create a really optimised lightweight Apache config to serve this with.

If you want to go for something even faster and are happy to not use Apache you could use lighttpd and it's mod_usertrack or nginx's HttpUserId module

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