问题
I have worker processes that needs gathered/calculated data as arguments on start up. This is then needed on re-starts as well. Where should I put the initialization code? Inside the supervisors init? Or inside the modules start_link, or init? Are there any best practices in Erlang when it comes to this?
回答1:
If the gen_server component has critical state, or state which cannot be re-calculated/re-gathered, I generally avoid keeping the state in gen_server itself. I instead choose to maintain state in an external process/ets table. If you are going by this approach, make sure the ets table is either created by an externel process (which you are sure will not die), for eg., the application process -or- create the ets table in the init method of the gen_server and use the "ets:give_away/3" method to hand it off to an external process (of course, you would need to check if the table is already created in the gen_server's init method).. Else the ets table will be destroyed when the process dies..
来源:https://stackoverflow.com/questions/4172381/data-persistence-when-worker-process-dies-how