Why is the Application Controller class variable in Rails reinitialized in another request

I have my own application controller called McController, which extends ApplicationController, and I set the class variable in McController, which is called @@ scheduler_map, as shown below:

class McController < ApplicationController @@scheduler_map = {} def action ... end private def get_scheduler(host, port) scheduler = @@scheduler_map[host+"_"+port] unless scheduler scheduler = Scheduler.create(host, port) @@scheduler_map[host+"_"+port] = scheduler end scheduler end end 

but I found that from the second start of the request to @@ scheduler_map there is always an empty hash, I run it in the development env, can anyone know the reason? what is related to running env?

Thanks in advance.

+7
source share
1 answer

You answered your question :-)

Yes, this is caused by the development environment (I tested it), or rather, the configuration option "config.cache_classes = false" in config / environment / development.rb

This flag will reload all classes on every request. This is done because then you do not have to restart the entire server when you make a small change for your controllers.

You might want to take into account that what you are trying to do may cause a leak in the HUGE memory when it is subsequently put into production with a lot of visits. Each time a user visits your site, he creates a new entrance to this hash and is never cleared. Imagine what would happen if 10,000 users visited your site? or about 1,000,000? All this data is stored in system memory, so it can take up a lot of space, the longer the server is on the network.

Also, I'm not sure if this solution will work on a production server. The server will create many threats to handle a large number of visitors at the same time. I think (not sure) that each threat will have its own instances of classes. This means that in interpretation 1, a schedule map for ip xx may exist, but in treatment 2 this is not so. If you give me more information about what this planner is, I can give a suggestion for another solution.

+9
source

All Articles