GenEvent สำหรับการจัดการเหตุการณ์
เรียนรู้การใช้ GenEvent เพื่อสร้างระบบจัดการเหตุการณ์แบบแยกจากกัน ทำให้ผู้เผยแพร่และผู้สมัครรับข้อมูลโต้ตอบกันแบบอะซิงโครนัส
GenEvent สำหรับการจัดการเหตุการณ์ เป็นบทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Erlang OTP: Distributed & Fault-Tolerant Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Event Handling?
Imagine you have many parts of your application that need to react to something happening, like a user logging in.
If each part directly calls every other part, your code becomes tightly coupled and hard to change. This is where event handling comes in!
Introducing GenEvent
Erlang's OTP (Open Telecom Platform) provides a powerful behavior called gen_event for building decoupled event handling systems.
- It implements the publisher-subscriber pattern.
- Publishers send events without knowing who will receive them.
- Subscribers (called handlers) register to receive specific events.
- This promotes loose coupling and makes systems more flexible.
The Event Manager
At the heart of gen_event is an event manager. This is a special Erlang process that acts as a central hub:
- It receives events from publishers.
- It dispatches these events to all registered handlers.
You start an event manager just like other OTP behaviors:
-module(event_manager_starter).
-export([start/0]).
start() ->
% Start a local event manager named 'my_app_events'
{ok, Pid} = gen_event:start_link({local, my_app_events}),
io:format("Event manager started with PID: ~p~n", [Pid]),
ok.Event Handlers: The Listeners
An event handler is an Erlang module that implements the gen_event behavior. It defines callback functions that the event manager will call when an event occurs.
Think of handlers as specialized listeners, each interested in certain types of events or performing a specific action when an event is received.
Creating a Simple Handler
Here's the basic structure for an event handler module. The key callback is handle_event/2, where you process the incoming event.
-module(my_event_handler).
-behaviour(gen_event).
-export([init/1, handle_event/2, terminate/2]).
init(Args) ->
io:format("Handler initialized with args: ~p~n", [Args]),
{ok, []}. % Returns initial state
handle_event(Event, State) ->
io:format("Handler received event: ~p~n", [Event]),
% Here you'd process the event
{ok, State}. % Return new state
terminate(_Args, _State) ->
io:format("Handler terminating.~n", []),
ok.Adding Handlers to the Manager
After starting your event manager and defining your handler, you need to tell the manager about your handler. This is done using gen_event:add_handler/3.
You can add multiple handlers to the same manager, and each will receive the events.
-module(handler_adder).
-export([add_to_manager/1]).
add_to_manager(ManagerName) ->
% The handler module name (my_event_handler)
% and any initial arguments for its init/1 function ([] in this case)
gen_event:add_handler(ManagerName, my_event_handler, []),
io:format("Handler 'my_event_handler' added to '~p'.~n", [ManagerName]),
ok.Notifying the Manager (Publishing Events)
Once handlers are registered, any part of your application can send an event to the manager using gen_event:notify/2. The manager will then forward this event to all active handlers.
The publisher doesn't know (or care) how many handlers there are, or what they do. This is the power of decoupling!
-module(event_publisher).
-export([send_alert/2]).
send_alert(ManagerName, Message) ->
Event = {alert, Message, os:timestamp()},
io:format("Publisher sending event: ~p to manager '~p'.~n", [Event, ManagerName]),
gen_event:notify(ManagerName, Event).Full GenEvent Demo
Let's put it all together! This runnable example starts a manager, adds a simple handler, and then sends a few events. Watch the handler react!
-module(gen_event_demo).
-export([start/0]).
% --- Inline Handler Module for Demo ---
% In a real app, this would be a separate .erl file.
my_demo_handler() ->
% Compile and load a temporary handler module
code:delete(demo_handler_impl),
code:purge(demo_handler_impl),
{ok, _} = compile:forms([
'-module(demo_handler_impl).',
'-behaviour(gen_event).',
'-export([init/1, handle_event/2, terminate/2]).',
'init(Args) -> {ok, Args}.',
'handle_event(Event, State) ->',
' io:format("*** Handler received: ~p~n", [Event]),',
' {ok, State}.',
'terminate(_Args, _State) -> ok.'
], []),
demo_handler_impl.
% --- Main Application Logic ---
start() ->
ManagerName = my_system_events,
HandlerModule = my_demo_handler(),
io:format("--- Starting GenEvent Demo ---~n"),
% 1. Start the event manager
{ok, _ManagerPid} = gen_event:start_link({local, ManagerName}),
io:format("Manager '~p' started.~n", [ManagerName]),
% 2. Add the handler to the manager
gen_event:add_handler(ManagerName, HandlerModule, []),
io:format("Handler '~p' added.~n", [HandlerModule]),
% 3. Publish some events
io:format("Sending first event...~n"),
gen_event:notify(ManagerName, {user_logged_in, "Alice"}),
timer:sleep(100), % Give time for event processing
io:format("Sending second event...~n"),
gen_event:notify(ManagerName, {sensor_reading, 25.5}),
timer:sleep(100),
io:format("Sending third event...~n"),
gen_event:notify(ManagerName, {error_alert, "Disk_full"}),
timer:sleep(100),
% 4. Stop the manager (optional, for clean exit)
gen_event:stop(ManagerName),
io:format("--- GenEvent Demo Finished ---~n"),
ok.Advanced GenEvent Usage
gen_event is quite flexible:
- Handler State: Handlers can maintain their own internal state, updated with each event.
- Multiple Handlers: A single event manager can have many handlers, each processing events independently.
- Removing Handlers: Handlers can be dynamically removed using
gen_event:delete_handler/3. - Synchronous Calls: While primarily asynchronous,
gen_event:call/2allows synchronous calls to handlers (though less common for pure eventing).
GenEvent Quick Check
You've learned about GenEvent's core components and how they interact. Let's test your understanding!
Recap: GenEvent Essentials
Great job! You've learned how gen_event helps build flexible, decoupled systems:
- Event Manager: The central hub that dispatches events.
- Event Handlers: Modules that subscribe to and process events.
- Publishers: Send events to the manager using
gen_event:notify/2. - Decoupling: Key benefit, allowing parts of your system to evolve independently.
Next, you'll explore even more advanced OTP behaviors!
เรียนรู้ Erlang ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “GenEvent สำหรับการจัดการเหตุการณ์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “GenEvent สำหรับการจัดการเหตุการณ์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Erlang OTP: Distributed & Fault-Tolerant Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Erlang OTP: Distributed & Fault-Tolerant Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “GenEvent สำหรับการจัดการเหตุการณ์”
เรียนรู้การใช้ GenEvent เพื่อสร้างระบบจัดการเหตุการณ์แบบแยกจากกัน ทำให้ผู้เผยแพร่และผู้สมัครรับข้อมูลโต้ตอบกันแบบอะซิงโครนัส คุณปฏิบัติ Erlang OTP: Distributed & Fault-Tolerant Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Erlang OTP: Distributed & Fault-Tolerant Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “GenEvent สำหรับการจัดการเหตุการณ์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming นี้ได้ไหม
ได้ บทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- GenStatem สำหรับการจัดการสถานะ
- GenEvent สำหรับการจัดการเหตุการณ์
- พฤติกรรม OTP แบบกำหนดเอง
- การสลับโค้ดแบบร้อนและการอัปเกรดขณะทำงาน