Erlang OTP Learning (1) gen_server

Source: Internet
Author: User

In the OTP Introduction section of programming Erlang, the author shows us the Gen_server design ideas in a gradual manner, and now summarizes:

Before we look at Gen_server, we'll look at a common server framework:


In this server, you can hardly see anything related to a specific function, it only provides a basic framework that the server has, how does it work?
When we call the start function, a service is started, and if the server receives a message, it will forward the message to Mod:handle_call or Mod:handle_cast and then return the execution result to the client (optional). Then continue to wait for new messages.

from this process, it is not difficult to find that the server is actually acting as the "agent" role, while the actual processing of the client request is actually another module (we call it: Callback module)

What good is this? I talk about my own humble opinion:
1. Decoupling, the server functional part and the non-public energy portion of the separation, so that we can focus more on the server function module writing (ie callback module)
2. reusability, if we want to develop a server with new functionality, we can reuse the existing server framework and then write the callback module with the new functionality

Now let's look at a callback module example (it provides the KV storage function)


Where Init, the Handle_call method is used for server-side callbacks, and the Add,find,start method is for the client to invoke the

Let's take a look at the results:


now let's take a simple analysis of the entire execution process:
Stroage:start () started a service called Kv_server and used the storage module as the callback module for the service, then blocked in the loop method, waiting for new messages to arrive .... At this time, when we call Storage:add (name, Diaocow), we send a request message {Add, name, Diaocow} to Kv_server, and when Kv_server receives the message, it does not handle it, Instead, it turns over to his callback module storage processing and returns the processed results to the client, and then continues waiting for the new message ...

As you can see, the server module acts as a proxy (accept client messages, send to callback module processing, and return processing results to the client), while the storage module gives the server callback (really responsible for handling client requests). On the other hand, the client is provided with an interface that can be called (for example, the add and find interfaces here).

When you need to modify the function of this server, only need to modify the callback module, is not very convenient ^_^


---------------------------------------------------------------------Ornate Split Line----------------------------------------------- --------------------


Say so much, so what is Gen_server? In fact, it provides a generic server framework similar to the above concepts, but more robust than we are, perfect, if you need to write a server with a feature, using Gen_server can let you focus on the function itself, that is, the callback module

So how do you write a Gen_server callback module? Only three steps
1. Give your callback module a name
2. Identify the interfaces that need to be provided to the outside (client)
3. Implement the callback interface required by the Gen_server


Now we use Gen_server to re-implement KV storage


Run the next program, everything OK


Now let's explain in detail the role of each of the methods in the New_storage module:

1.-behaviour (gen_server)
It means that the compiler checks to see if the current module implements all of the callback interfaces specified by Gen_server, and if I comment out a callback interface (such as CODE_CHANGE/3), it will be reported at compile time:


2.gen_server:start_link (ServerName, Module, Args, Options), Result
This method is used to start a server where:
parameter servername Specifies the service name
The parameter module specifies the callback module for the server
The parameter Args will be initialized as a service startup parameter (invoked when the service initializes: Module:init ([Args]))
Parameter options Specify some characteristic parameters, which can usually be used directly []

If the service starts successfully, return {OK, Pid}

3.module:init ([Args])
This method will be callback when the service is initialized, the parameter args is the second-to-last parameter in the Gen_server:start_link, if the initialization succeeds, the method put back {OK, State}, where it will act as the state that started the service

4.gen_server:call (Serverref, Request)
This method is for the callback module to send request requests to the service represented by the Serverref (the callback module typically encapsulates a layer of interfaces on top of the client, such as the Add,find method here), noting that the method is aSynchronous Invocation, it waits for the server to return a response message (unless wait timeout, default 5s)

5.module:handle_call (Request, from, state), Result
This is a callback method to handle requests made by Gen_server:call (Serverref, request), Where:
Request, which indicates that the client requested
From that indicates which client the request came from
State, which indicates the current server status

Result for Handle_call request processing results, it has the following types
{Reply,reply,newstate}
{Reply,reply,newstate,timeout}
{Reply,reply,newstate,hibernate}
{Noreply,newstate}
{Noreply,newstate,timeout}
{Noreply,newstate,hibernate}
{Stop,reason,reply,newstate} | {Stop,reason,newstate}

What is the difference between these kinds of return values?
If the return starts with reply, then reply will be returned to the client as a response
If the return starts with noreply, then the server will not return any messages to the client (this will cause the client to block because the Gen_server:call method called by the client is a synchronous call, and when it makes a request, it waits for the server to send a response message, unless the wait times out)

6.gen_server:cast (Serverref, Request)
This method is the same as Gen_server:call (Serverref, Request), but its biggest difference is that the call isof asynchronous, it does not need to wait for the server to return any processing results

7.module:handle_cast (Request, state), Result
This method is used to process requests made by Gen_server:cast (Serverref, request), because no results are returned to the client, so the parameter list does not have a from

For more APIs on Gen_server, see: http://www.erlang.org/doc/man/gen_server.html
OTP Official document: Http://www.erlang.org/doc/design_principles/gen_server_concepts.html


Now that we have gen_server the general idea of design, that is: Gen_server implements a generic server framework, if we need to develop a function, just follow the Gen_server callback interface specification, write the corresponding callback Module can

Erlang OTP Learning (1) gen_server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.